여기에 설명 된대로 리플렉션을 사용하여이 작업을 수행 할 수 있어야합니다.
링크가 죽었 기 때문에 웨이 백 머신에서 관련 세부 정보를 찾았습니다.
정적 제네릭 메서드가있는 클래스가 있다고 가정합니다.
class ClassWithGenericStaticMethod
{
public static void PrintName<T>(string prefix) where T : class
{
Console.WriteLine(prefix + " " + typeof(T).FullName);
}
}
반사를 사용하여이 메서드를 어떻게 호출 할 수 있습니까?
이것은 매우 쉬운 것으로 밝혀졌습니다. 이것은 리플렉션을 사용하여 정적 제네릭 메서드를 호출하는 방법입니다.
// Grabbing the type that has the static generic method
Type typeofClassWithGenericStaticMethod = typeof(ClassWithGenericStaticMethod);
// Grabbing the specific static method
MethodInfo methodInfo = typeofClassWithGenericStaticMethod.GetMethod("PrintName", System.Reflection.BindingFlags.Static | BindingFlags.Public);
// Binding the method info to generic arguments
Type[] genericArguments = new Type[] { typeof(Program) };
MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(genericArguments);
// Simply invoking the method and passing parameters
// The null parameter is the object to call the method from. Since the method is
// static, pass null.
object returnValue = genericMethodInfo.Invoke(null, new object[] { "hello" });