싱글 톤 객체에서 반사를 사용하여 메소드를 호출합니다
-
03-07-2019 - |
문제
그래서 나는 다음과 같습니다.
public class Singleton
{
private Singleton(){}
public static readonly Singleton instance = new Singleton();
public string DoSomething(){ ... }
public string DoSomethingElse(){ ... }
}
반사를 사용하여 Dosomething 방법을 어떻게 호출 할 수 있습니까?
내가 묻는 이유는 메소드 이름을 XML에 저장하고 UI를 동적으로 생성하기 때문입니다. 예를 들어 버튼을 동적으로 생성하고 버튼을 클릭 할 때 반사를 통해 호출 할 방법을 알려줍니다. 어떤 경우에는 복용량이거나 다른 경우에는 복용 할 수 있습니다.
해결책
테스트되지 않았지만 작동해야합니다 ...
string methodName = "DoSomething"; // e.g. read from XML
MethodInfo method = typeof(Singleton).GetMethod(methodName);
FieldInfo field = typeof(Singleton).GetField("instance",
BindingFlags.Static | BindingFlags.Public);
object instance = field.GetValue(null);
method.Invoke(instance, Type.EmptyTypes);
다른 팁
잘 했어. 감사.
원격 어셈블리를 참조 할 수없는 경우에 대해 약간 수정 된 동일한 접근법이 있습니다. 클래스 풀 이름 (IE Namespace.className 및 원격 어셈블리 경로)과 같은 기본 사항을 알아야합니다.
static void Main(string[] args)
{
Assembly asm = null;
string assemblyPath = @"C:\works\...\StaticMembers.dll"
string classFullname = "StaticMembers.MySingleton";
string doSomethingMethodName = "DoSomething";
string doSomethingElseMethodName = "DoSomethingElse";
asm = Assembly.LoadFrom(assemblyPath);
if (asm == null)
throw new FileNotFoundException();
Type[] types = asm.GetTypes();
Type theSingletonType = null;
foreach(Type ty in types)
{
if (ty.FullName.Equals(classFullname))
{
theSingletonType = ty;
break;
}
}
if (theSingletonType == null)
{
Console.WriteLine("Type was not found!");
return;
}
MethodInfo doSomethingMethodInfo =
theSingletonType.GetMethod(doSomethingMethodName );
FieldInfo field = theSingletonType.GetField("instance",
BindingFlags.Static | BindingFlags.Public);
object instance = field.GetValue(null);
string msg = (string)doSomethingMethodInfo.Invoke(instance, Type.EmptyTypes);
Console.WriteLine(msg);
MethodInfo somethingElse = theSingletonType.GetMethod(
doSomethingElseMethodName );
msg = (string)doSomethingElse.Invoke(instance, Type.EmptyTypes);
Console.WriteLine(msg);}
제휴하지 않습니다 StackOverflow