문제

공장 패턴 스타일 기능에서 다음 코드를 사용하고 있습니다.

공개 클래스 SingleItemnew : CheckoutContext {public bookingcontext data {get; 세트; } public SingleItemnew (BookingContext Data) {data = data; }} public CheckoutContext findContext (BookingContext Data) {type ContextType = type.getType ( "CheckoutProcesses." + data.case.toString ()); CheckoutContext로 CheckoutContext (ContextType, bindingflags.createInstance, new [] {data}) checkoutContext output = activator.createInstance (contextType, bindingflags.createInstance); 리턴 출력; }

그러나 실행 중에는 예외를 찾을 수없는 멤버를 던지므로 그 이유를 알 수 없습니다.

data.case.toString () 메소드는 단일 인수를받는 생성자가있는 클래스의 이름 인 SingleItemnew의 이름을 반환합니다.

누구든지 문제가 무엇인지 아는 사람이 있습니까?

건배, 에디션

도움이 되었습니까?

해결책

이거 한번 해봐:

  Type contextType = Type.GetType("CheckoutProcesses." + data.Case.ToString());
  CheckoutContext output = 
      (CheckoutContext)Activator.CreateInstance(contextType, data);

코드가 작동하지 않는 이유는 Activator.CreateInstance 실제로 원하는 과부하가 없습니다. 따라서 코드가 왜 컴파일되는지 궁금 할 것입니다! 그 이유는 (Type type, params object[] args) 메소드 호출과 일치하여 컴파일하지만 런타임에 생성자가 BindingFlags 그리고 a BookingContext[] 그것은 분명히 당신의 유형이 가진 것이 아닙니다.

다른 팁

생성자가 공개됩니까?

유형의 단일 매개 변수입니다 BookingContext?

문제는 이것은 분명히 더 큰 시스템의 일부입니다. 많이 당신이 생산할 수 있다면 당신을 도울 수 있습니다 짧지 만 완전한 프로그램 문제를 보여주었습니다. 그런 다음 해당 프로그램의 문제를 해결할 수 있으며 수정 사항을 실제 시스템으로 다시 포팅 할 수 있습니다. Otherwisewise 우리는 정말로 추측하고 있습니다 :(

SingleItemnew 생성자가 Parameter로 BookingContext를 취합니까? Exatcly와 일치하지 않으면 실패합니다.

class ParamType   {    }
class DerivedParamType : ParamType    {    }
class TypeToCreate
{
    public TypeToCreate(DerivedParamType data)
    {
        // do something
    }
}

ParamType args = new ParamType();
// this call will fail: "constructor not found"
object obj = Activator.CreateInstance(typeof(TypeToCreate), new object[] { args });

// this call would work, since the input type matches the constructor
DerivedParamType args = new DerivedParamType();
object obj = Activator.CreateInstance(typeof(TypeToCreate), new object[] { args });

이것은 나를 위해 효과가있었습니다.

type.getType ( "namespace.class, 네임 스페이스");

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top