[英]How to create a delegate for a generic method?
我有一堂簡單的課:
class Test
{
public static int Test<T>(T arg)
{
return 1;
}
}
我想獲得代表此方法的Delegate
類型的對象。 是否可以創建這樣的委托? 如果我可以將具有任意數量的參數和通用參數的方法轉換為Delegate
,那就更好了。
您不想在這里使用委托。 您需要一個MethodInfo
實例:
void ImportMethod(string name, MethodInfo method)
您可以這樣稱呼它:
void ImportMethod("Test", typeof(Test).GetMethod("Test", ...Static));
如果使用泛型編寫方法以保持類型安全,則將需要為每個具有不同輸入參數量的方法編寫兩個方法,一個用於void方法(Action),一個用於返回值的方法(Func)。 我加入了一個輔助類,因為它減少了每次方法導入都必須傳遞的通用參數的數量。 調用該方法時,它還有助於智能感知。
public class Foo
{
public void Bar()
{
}
public void Bar(string input)
{
}
public bool BarReturn()
{
return false;
}
}
public class ImportHelper<TClass>
{
public void Import(string name, Expression<Action<TClass>> methodExpression)
{
ImportMethod(name, methodExpression);
}
public void ImportMethodWithParam<TParam>(string name, Expression<Action<TClass, TParam>> methodExpression)
{
ImportMethod<TClass, TParam>(name, methodExpression);
}
public void ImportMethodWithResult<TResult>(string name, Expression<Func<TClass, TResult>> methodExpression)
{
ImportMethod<TClass, TResult>(name, methodExpression);
}
}
private static void TestImport()
{
ImportMethod<Foo>("MyMethod", f => f.Bar());
ImportMethod<Foo, string>("MyMethod1", (f, p) => f.Bar(p));
ImportMethod<Foo, bool>("MyMethod2", f => f.BarReturn());
var helper = new ImportHelper<Foo>();
helper.Import("MyMethod", f => f.Bar());
helper.ImportMethodWithParam<string>("MyMethod1", (f, p) => f.Bar(p));
helper.ImportMethodWithResult("MyMethod2", f => f.BarReturn());
}
public static void ImportMethod<TClass>(string name, Expression<Action<TClass>> methodExpression)
{
var method = GetMethodInfo(methodExpression.Body as MethodCallExpression);
//Do what you want with the method.
}
public static void ImportMethod<TClass, TParam>(string name, Expression<Action<TClass, TParam>> methodExpression)
{
var method = GetMethodInfo(methodExpression.Body as MethodCallExpression);
//Do what you want with the method.
}
public static void ImportMethod<TClass, TResult>(string name, Expression<Func<TClass, TResult>> methodExpression)
{
var method = GetMethodInfo(methodExpression.Body as MethodCallExpression);
//Do what you want with the method.
}
private static MethodInfo GetMethodInfo(MethodCallExpression methodCallExpression)
{
if (methodCallExpression == null)
return null;
return methodCallExpression.Method;
}
public delegate int Del<T>(T item);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.