1
下面定義的類型是什麼,我想實現從靜態方法在泛型類型返回System.Action在運行時
public class CoolClass<T>
{
public static void DoSomethingCool()
{
// Insert cool generic stuff here.
List<T> coolList = new List<T>();
}
}
public class OtherClass
{
public Action ReturnActionBasedOnStaticGenericMethodForType(Type type)
{
// Ideally this would just be
return CoolClass<type **insert magic**>.DoSomethingCool
}
}
我知道,如果類型是已知的,我可以做下面的一個非常配對下來例如它將返回System.Action
return CoolClass<string>.DoSomethingCool
我知道,如果我想要做的是調用的方法我可以做
Type baseType = typeof(CoolClass<>);
Type[] typeArguments = new [] {type}
Type constructedType = baseType.MakeGenericType(typeArguments);
MethodInfo method = constructedType.GetMethod("DoSomethingCool");
method.Invoke(null,null);
我可能一起走錯路。這似乎是我試圖去獲得method
作爲DoSomethingCool
方法的參考。我希望得到(Action) method
之類的東西。
啊,這麼近。我意識到,如果我創建另一個名爲GetDoSomethingCool的靜態方法,例如,返回DoSomethingCool也會起作用。你的解決方案更加優雅。 – btlog 2012-02-24 22:42:34