何らかの方法で(またはその両方)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]); –
それははるかに複雑です...ハングアップします。 –
さて、それほど複雑ではないかもしれない...更新を見てください。 –