Ponteiros de função em c #
Eu suponho de alguma forma, quer (ou ambos)Delegate
ouMethodInfo
qualificar para este título. No entanto, nenhum dos dois fornece a gentileza sintática que estou procurando. Então, em suma, existe alguma maneira que eu possa escrever o seguinte:
FunctionPointer foo = // whatever, create the function pointer using mechanisms
foo();
Eu não posso usar um delegado sólido (ou seja, usando odelegate
palavra-chave para declarar um tipo de delegado) porque não há como saber até o tempo de execução a lista de parâmetros exatos. Para referência, aqui está o que eu tenho brincado no LINQPad atualmente, ondeB
será (principalmente) código gerado pelo usuário, e assim seráMain
e, portanto, por gentileza para os meus usuários, estou tentando remover o.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.");
}
}