【发布时间】:2016-11-04 16:58:18
【问题描述】:
我正在努力使用可以使用反射检索的MethodInfo 创建Action<> 的实例。
使用下面的示例,我可以轻松地在我的对象上调用自定义方法,但我真的很想将它们转换为动作。
我已经尝试使用 Delegate.CreateDelegate 来实现它,但我似乎无法让它返回一个泛型类型的 Action。
示例
我已经创建了如下界面:
interface IMyTest { } // Marker interface
interface<TInput> IMyTest : IMyTest {
void MyMethod(TInput input);
}
然后我在一个类中继承接口:
class MyClass : IMyTest<DateTime>, IMyTest<int> {
void MyMethod(DateTime input) {
// Do something
}
void MyMethod(int input) {
// Do something else
}
}
然后我创建一个使用反射从接口实例中查找并调用“MyMethod”的方法:
void DoCallMyMethod(object target, object input) {
IEnumerable<Type> interfaces = target.GetType().GetInterfaces()
.Where(x => typeof(IMyTest).IsAssignableFrom(x) && x.IsGenericType);
foreach (Type @interface in interfaces) {
Type type = @interface.GetGenericArguments()[0];
MethodInfo method = @interface.GetMethod("MyMethod", new Type[] { type });
if (method != null) {
method.Invoke(target, new[] { input });
}
}
}
最后我把它们放在一起:
MyClass foo = new MyClass();
DoCallMyMethod(foo, DateTime.Now);
DoCallMyMethod(foo, 47);
我想要什么
在DoCallMyMethod 内部,我希望将MethodInfo method 转换为通用Action,以便结果如下所示:
Action<type> myAction = method;
但这显然行不通。
我发现了一些类似的 SO 帖子(但没有一个完全涵盖我的情况),最终得到的答案类似于:
Action<object> action =
(Action<object>)Delegate.CreateDelegate(typeof(Action<object>), target, method);
但这不起作用,因为“无法绑定到目标方法,因为它的签名或安全透明度与委托类型的不兼容。”
我怎样才能得到一个以指定type 作为输入类型的动作,同时仍然保留对象引用(不出现新实例)?
【问题讨论】:
标签: c# generics reflection delegates action