我想在某些方面(或兩者)Delegate
或MethodInfo
有資格這個稱號。但是,既沒有提供我正在尋找的語法好處。因此,簡而言之,有沒有一些辦法,我可以寫:函數指針在C#
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.");
}
}
雖然我認爲你是一個思考這個問題的天才,但我在嘗試使用以下代碼創建委託時遇到了綁定錯誤:return(DynamicFunction)Delegate。CreateDelegate(typeof(DynamicFunction), \t \t \t \t this,functions [function]); – 2009-07-26 11:43:04
這很複雜......掛在上面。 – 2009-07-26 11:45:53