我有一个简单的课程:
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);