C# 在运行时定义了类型的泛型类型上从静态方法返回System.Action
下面是一个非常成对的例子,说明我正在努力实现的目标C# 在运行时定义了类型的泛型类型上从静态方法返回System.Action,c#,reflection,C#,Reflection,下面是一个非常成对的例子,说明我正在努力实现的目标 public class CoolClass<T> { public static void DoSomethingCool() { // Insert cool generic stuff here. List<T> coolList = new List<T>(); } } public class OtherClass { public
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
}
}
公共类
{
公共静态void DoSomethingCool()
{
//在这里插入很酷的通用材料。
List coolList=新列表();
}
}
公共类其他类
{
公共操作ReturnActionBasedOnStaticGenericMethodForType(类型)
{
//理想情况下,这只是
返回CoolClass.DoSomethingCool
}
}
我知道如果已知类型,我可以执行以下操作,它将返回System.Action
return CoolClass<string>.DoSomethingCool
return CoolClass.DoSomethingCool
我知道如果我只想调用我能做的方法
Type baseType = typeof(CoolClass<>);
Type[] typeArguments = new [] {type}
Type constructedType = baseType.MakeGenericType(typeArguments);
MethodInfo method = constructedType.GetMethod("DoSomethingCool");
method.Invoke(null,null);
Type baseType=typeof(CoolClass);
Type[]typeArguments=new[]{Type}
类型constructedType=baseType.MakeGenericType(类型参数);
MethodInfo method=constructedType.GetMethod(“doSomethingTool”);
调用(null,null);
我可能一起走错了路。似乎我正在尝试获取
method
作为DoSomethingCool
方法的参考。我希望得到类似于(Action)method
的东西,您就快到了-您只需要:
啊,好近啊。我确实意识到,如果我创建了另一个名为GetDoSomethingCool的静态方法,该方法返回的DoSomethingCool也可以工作。您的解决方案更加优雅。
Action action = (Action) Delegate.CreateDelegate(typeof(action), null, method);