我想要做的是以下(我不知道它是否可能);我知道一个运行时间类型。我知道我想在运行时调用哪种方法。但是,我不知道这在编译时间。C#在运行时创建参数类型未知的方法代理
由于inparam不是类型对象,因此GetFunction方法将无法创建给定methodInfo的委托。
有没有办法创建一个函数的委托,我只知道我希望委托的方法的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是框架,所以这样做更有意义。你为什么要求你的密封? – sydan 2014-10-31 08:51:13