如果你有一个泛型方法,你可以通过反射调用它MethodInfo
。
首先为方法的每个泛型类型参数调用MethodInfo
一种MethodInfo MakeGenericMethod(params Type[] typeArguments)
类型。
然后使用您希望在其上调用方法的对象的实例(或者MethodInfo
如果它是一个方法)调用结果,以及按顺序包含该方法的参数的对象数组。object Invoke(object obj, object[] parameters)
null
static
这是修改后的 C# 代码,用于编译、运行和执行某些操作。Example1()
是您的第一个代码段。Example2()
做你想让你的第二个代码片段做的事情。
public class SomeBaseClass {
public string someProperty {
set {
Console.WriteLine(string.Format("someProperty called on {0} with {1}", this, value ) );
}
}
}
public class Foo : SomeBaseClass {
}
public class Bar : SomeBaseClass {
}
public class Baz : SomeBaseClass {
}
public static class SomeMethods {
public static T SomeMethod<T>() where T : SomeBaseClass, new() {
return new T();
}
}
class Program
{
public static void Example1() {
string someValue = "called from Example1";
SomeMethods.SomeMethod<Foo>().someProperty = someValue;
SomeMethods.SomeMethod<Bar>().someProperty = someValue;
SomeMethods.SomeMethod<Baz>().someProperty = someValue;
}
public static void Example2() {
string someValue = "called from Example2";
Type[] types = new Type[]{
typeof(Foo), typeof(Bar), typeof(Baz), //...
};
foreach (Type type in types) {
// Here's how:
System.Reflection.MethodInfo genericMethodInfo = typeof(SomeMethods).GetMethod("SomeMethod");
System.Reflection.MethodInfo methodInfoForType = genericMethodInfo.MakeGenericMethod(type);
var someBase = (SomeBaseClass) methodInfoForType.Invoke(null, new object[] { });
someBase.someProperty = someValue;
}
}
static void Main(string[] args)
{
Console.WriteLine("Example1");
Example1();
Console.WriteLine("Example2");
Example2();
Console.ReadKey();
}
}
这是程序的输出:
Example1
someProperty called on ConsoleApplication1.Foo with called from Example1
someProperty called on ConsoleApplication1.Bar with called from Example1
someProperty called on ConsoleApplication1.Baz with called from Example1
Example2
someProperty called on ConsoleApplication1.Foo with called from Example2
someProperty called on ConsoleApplication1.Bar with called from Example2
someProperty called on ConsoleApplication1.Baz with called from Example2