developer tip

C # 리플렉션을 사용하여 생성자 호출

optionbox 2020. 9. 9. 07:55
반응형

C # 리플렉션을 사용하여 생성자 호출


다음과 같은 시나리오가 있습니다.

class Addition{
 public Addition(int a){ a=5; }
 public static int add(int a,int b) {return a+b; }
}

다음과 같이 다른 클래스에서 추가를 호출합니다.

string s="add";
typeof(Addition).GetMethod(s).Invoke(null, new object[] {10,12}) //this returns 22

다음을 사용하여 Addition 유형의 새 개체를 만들려면 위의 리플렉션 문과 유사한 방법이 필요합니다. Addition(int a)

그래서 나는 string을 가지고 있으며 s= "Addition", 반사를 사용하여 새로운 객체를 만들고 싶습니다.

이게 가능해?


나는 생각하지 않는다 GetMethod아니, 그것을 할 것입니다 -하지만 GetConstructor것입니다.

using System;
using System.Reflection;

class Addition
{
    public Addition(int a)
    {
        Console.WriteLine("Constructor called, a={0}", a);
    }
}

class Test
{
    static void Main()
    {
        Type type = typeof(Addition);
        ConstructorInfo ctor = type.GetConstructor(new[] { typeof(int) });
        object instance = ctor.Invoke(new object[] { 10 });
    }
}

편집 : 예, Activator.CreateInstance너무 작동합니다. 사용 GetConstructor당신이 일보다 효율적으로 제어 할 것인지 등의 매개 변수 이름을 찾아, Activator.CreateInstance당신이 경우 대단한 단지 비록 생성자를 호출하고 싶습니다.


예, 사용할 수 있습니다 Activator.CreateInstance

참고 URL : https://stackoverflow.com/questions/3255697/using-c-sharp-reflection-to-call-a-constructor

반응형