Compact Framework- 기본 생성자가없는 유형을 동적으로 생성하는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/29436

문제

.NET CF 3.5를 사용하고 있습니다. 작성하려는 유형에는 기본 생성자가 없으므로 문자열을 과부하 된 생성자로 전달하려고합니다. 어떻게해야합니까?

암호:

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
도움이 되었습니까?

해결책

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 });

다른 팁

@jonathan은 컴팩트 프레임 워크가 가능한 한 슬림해야하기 때문입니다. 내가 게시 한 코드와 같은 다른 방법이 있다면 일반적으로 기능을 복제하지 않습니다.

Rory Blyth는 한때 Compact 프레임 워크를 "시스템 주위의 래퍼. :)

좋아, 여기에 다양한 매개 변수가 주어진 유형을 활성화하는 유연한 방법을 제공하는 펑키 한 도우미 방법이 있습니다.

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;

따라서 어셈블리와 유형의 이름을 처음 두 매개 변수로 전달한 다음 모든 생성자의 매개 변수를 순서대로 전달합니다.

이것이 당신에게 효과가 있는지 확인하십시오 (비정상적인) :

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;

유형에 하나 이상의 생성자가 있으면 문자열 매개 변수를 수락하는 것을 찾기 위해 멋진 발판을해야 할 수도 있습니다.

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

edit2 : 크리스의 대답 내가 말한 멋진 발자국을 보여줍니다! ;-)

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