【发布时间】:2009-07-26 11:26:49
【问题描述】:
我想在某些方面,Delegate 或 MethodInfo 中的任何一个(或两者)都符合这个称号。但是,两者都没有提供我正在寻找的语法上的好处。所以,简而言之,有什么方法可以写出以下内容:
FunctionPointer foo = // whatever, create the function pointer using mechanisms
foo();
我不能使用实体委托(即,使用delegate 关键字来声明委托类型),因为直到运行时才能知道确切的参数列表。作为参考,这是我目前在 LINQPad 中一直在玩的东西,其中B 将(主要)是用户生成的代码,Main 也是如此,因此为了对我的用户更好,我正在尝试删除.Call:
void Main()
{
A foo = new B();
foo["SomeFuntion"].Call();
}
// Define other methods and classes here
interface IFunction {
void Call();
void Call(params object[] parameters);
}
class A {
private class Function : IFunction {
private MethodInfo _mi;
private A _this;
public Function(A @this, MethodInfo mi) {
_mi = mi;
_this = @this;
}
public void Call() { Call(null); }
public void Call(params object[] parameters) {
_mi.Invoke(_this, parameters);
}
}
Dictionary<string, MethodInfo> functions = new Dictionary<string, MethodInfo>();
public A() {
List<MethodInfo> ml = new List<MethodInfo>(this.GetType().GetMethods());
foreach (MethodInfo mi in typeof(Object).GetMethods())
{
for (int i = 0; i < ml.Count; i++)
{
if (ml[i].Name == mi.Name)
ml.RemoveAt(i);
}
}
foreach (MethodInfo mi in ml)
{
functions[mi.Name] = mi;
}
}
public IFunction this[string function] {
get {
if (!functions.ContainsKey(function))
throw new ArgumentException();
return new Function(this, functions[function]);
}
}
}
sealed class B : A {
public void SomeFuntion() {
Console.WriteLine("SomeFunction called.");
}
}
【问题讨论】:
标签: c# reflection delegates