어떤 식 으로든 (또는 둘 다) 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]); –
그것은 훨씬 더 복잡합니다. 잠시만 기다려주세요. –
좋아요, 그 복잡한 것은 아니지만 ... 업데이트를 참조하십시오. –