반응형
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
반응형
'developer tip' 카테고리의 다른 글
Xcode 6/7/8에서 디버그 빌드와 릴리스 빌드간에 어떻게 전환합니까? (0) | 2020.09.09 |
---|---|
DOM 노드의 문자열 표현 가져 오기 (0) | 2020.09.09 |
자바 스크립트 : 연관 배열에서 정수를 키로 사용합니까? (0) | 2020.09.09 |
Pandas의 크고 지속적인 DataFrame (0) | 2020.09.09 |
TFS에서 다른 사용자의 체크 아웃을 실행 취소하는 방법은 무엇입니까? (0) | 2020.09.09 |