【发布时间】:2014-10-31 08:38:33
【问题描述】:
我想要做的是以下(我一定不知道它是否可能);我知道运行时类型。我知道我想在运行时调用哪个方法。但是,我在编译时不知道这一点。
GetFunction 方法将无法创建给定 methodInfo 的委托,因为 inparam 不是对象类型。
有没有办法创建一个函数的委托,而我只知道我希望委托的方法的 Type 和 MethodInfo?
public sealed class Functions {
public static int SetStrValue(string s) {
// set a string
}
public static int SetIntValue(int i) {
// set an int
}
}
public sealed class GetFunctions {
public Func<object, int> GetFunction(Type type, MethodInfo methodInfo) {
// what I would like to do.
Func<object, int> func = Delegate.CreateDelegate(typeof(Func<object, int>), methodInfo);
return t => func(t);
}
}
public class InvokeFunctions {
public void invokeFunction() {
Type t = typeof(String);
MethodInfo methodInfo = typeof(Functions).GetMethod("SetStrValue");
int i = GetFunctions.GetFunction(t, methodInfo).Invoke("hello");
}
}
【问题讨论】:
-
从问题本身的一个方面来说,为什么你们的课程是密封的?这通常不是一个好主意,因为它基本上是在说“我永远不想扩展这个类或以任何方式改变它”,而许多 .NET 类是密封的,这更有意义,因为 .NET 是框架。为什么你要求你的密封?
标签: c# types parameters delegates runtime