2008-08-27 4 views
6

.NET CF 3.5를 사용하고 있습니다. 생성하려는 유형에 기본 생성자가 없으므로 문자열을 오버로드 된 생성자에 전달하려고합니다. 어떻게해야합니까?Compact Framework - 기본 생성자가없는 형식을 동적으로 만드는 방법은 무엇입니까?

코드 :이 당신을 위해 작동하는 경우

Assembly a = Assembly.LoadFrom("my.dll"); 
Type t = a.GetType("type info here"); 
// All ok so far, assembly loads and I can get my type 

string s = "Pass me to the constructor of Type t"; 
MyObj o = Activator.CreateInstance(t); // throws MissMethodException 

답변

9
MyObj o = null; 
Assembly a = Assembly.LoadFrom("my.dll"); 
Type t = a.GetType("type info here"); 

ConstructorInfo ctor = t.GetConstructor(new Type[] { typeof(string) }); 
if(ctor != null) 
    o = ctor.Invoke(new object[] { s }); 
0

이 (검증되지 않은) 참조 : 유형이 다음 하나 이상의 생성자가

Type t = a.GetType("type info here"); 
var ctors = t.GetConstructors(); 
string s = "Pass me to the ctor of t"; 
MyObj o = ctors[0].Invoke(new[] { s }) as MyObj; 

경우에 당신은을 찾기 위해 몇 가지 화려한 발놀림을 할 수 있습니다 하나는 문자열 매개 변수를 받아들입니다.

편집 : 코드를 테스트하기 만하면 작동합니다.

편집 2 : Chris' answer은 내가 말하는 멋진 발놀림을 보여줍니다! ;-)

4

@ 조나단 Compact Framework는 가능한 한 슬림해야하기 때문에. 다른 방법 (예 : 게시 된 코드)이있는 경우 일반적으로 기능을 복제하지 않습니다.

Rory Blyth는 Compact Framework를 "System.NotImplementedExcetion을 둘러싼 래퍼"라고 설명했습니다. :)

1

좋아, 여기에 매개 변수의 배열을 지정해, 당신에게 유형을 활성화 할 수있는 유연한 방법을 제공하는 펑키 도우미 메서드입니다 :

static object GetInstanceFromParameters(Assembly a, string typeName, params object[] pars) 
{ 
    var t = a.GetType(typeName); 

    var c = t.GetConstructor(pars.Select(p => p.GetType()).ToArray()); 
    if (c == null) return null; 

    return c.Invoke(pars); 
} 

는 그리고 당신은 다음과 같이 호출 :

Foo f = GetInstanceFromParameters(a, "SmartDeviceProject1.Foo", "hello", 17) as Foo; 

그래서 첫 번째 두 매개 변수로 어셈블리와 형식 이름을 전달한 다음 모든 생성자의 매개 변수를 순서대로 전달합니다.