2014-03-03 2 views
0

Reflection을 사용하여 메소드에 생성자를 호출하는 것이 가능한지 궁금해서 className을 메소드에 문자열로 전달하도록했습니다. 이것은 명령 해석의 맥락에서 수행됩니다. 전환 진술을 피하려고합니다 (학교에서 이상한 과제가 있고 시험에 대한 바로 가기를 찾고 있습니다).메서드에서 문자열 매개 변수로 생성자를 호출 할 수 있습니까?

Class SomeClass 
    { 
     //irrelevant code here 

     public BaseClass SomeMethod(string constructorName) 
     { 
     //call constructor here through string parameter to avoid switch statements 
     //for example string constructorName=SomeDerivedClassName 
     // and the result should be: 
     return SomeDerivedClassName(this.SomeProperty,this.SomeOtherPropertY); 
     } 

    } 

답변

2

같은 시도 : 클래스가 다른 어셈블리에있을 따라 코드를 수정할 수 있다면 물론

class SomeClass 
{ 
    //irrelevant code here 

    public BaseClass SomeMethod(string constructorName) 
    { 
    // possibly prepend namespace to 'constructorName' string first 

    var assemblyToSearch = typeof(SomeClass).Assembly; 
    var foundType = assemblyToSearch.GetType(constructorName); 

    return (BaseClass)Activator.CreateInstance(foundType, 
     this.SomeProperty, this.SomeOtherPropertY); 
    } 
} 

합니다.

이 질문은 생성자가 public 인 것으로 가정합니다.

+0

아래 테스트 솔루션을 게시 해 주셔서 감사합니다. 그런데 public으로 선언하지 않으면 생성자를 찾지 못합니다. –

관련 문제