2013-02-20 64 views
2

我試圖構建一個字典,它將一個類中的每個靜態方法編入索引,以便可以用字符串查找它們。我似乎無法找到一種方法來實際從MethodInfo中獲取參考。這可能嗎?如何從MethodInfo(C#)獲取對方法的引用

delegate void SkillEffect(BattleActor actor, BattleActor target); 

public static class SkillEffectLookup 
{ 
    public static Dictionary<string, SkillEffect> lookup; 

    public static void Build() 
    { 
     lookup = new Dictionary<string, SkillEffect>(); 
     Type type = typeof(SkillEffects); 
     var methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public); 
     foreach (MethodInfo methodInfo in methods) 
     { 
      lookup.Add(methodInfo.Name, _____________); 
     } 
    } 

public static class SkillEffects 
{ 
    public static Attack(BattleActor actor, BattleActor target) 
    { 
     // Do Things 
    } 

    public static NonAttack(BattleActor actor, BattleActor target) 
    { 
     // Do Other Things 
    } 
} 
+0

我想你想使用'Delegate.CreateDelegate'方法。有了這個,你可以使用你的'MethodInfo'創建和存儲委託給方法。 – 2013-02-20 19:09:57

+0

[可以從MethodInfo對象獲得Func (或類似)嗎?](http://stackoverflow.com/questions/2933221/can-you-get-a-funct-or-similar-from- a-methodinfo-object) – 2013-02-20 19:22:52

回答

2

嘗試使用CreateDelegate方法。只有當你知道方法的簽名時它纔會起作用。

http://msdn.microsoft.com/en-us/library/system.delegate.createdelegate.aspx

UPD(TNX克里斯·辛克萊):使用

lookup.Add(methodInfo.Name 
     , (SkillEffect)Delegate.CreateDelegate(typeof(SkillEffect), methodInfo)); 
+0

也許添加相關的代碼行ustor要求:'lookup.Add(methodInfo.Name,(SkillEffect)Delegate.CreateDelegate(typeof(SkillEffect),methodInfo));' – 2013-02-20 19:12:43

0

MethodInfo是該方法的元數據。要實際調用您調用的方法(驚喜!)MethodInfo.Invoke。

這是否回答你的問題?

0

如果你正在尋找保存方法本身的引用,因此你可以調用的

例子它,我不認爲你可以。真的是你做的是通過Invoke方法上MethodInfo稱之爲:

 foreach (MethodInfo methodInfo in methods) 
     { 
      lookup.Add(methodInfo.Name, _____________); 
     } 

然後把它稱之爲:

lookup[methodName].Invoke(null, BindingFlags.Public | BindingFlags.Static, null, args, null); 
+0

技術上沒有函數點在C#中(除非你喜歡不安全的代碼),所以沒有你不能,但我認爲OP實際上是在談論委託,你可以從MethodInfo對象創建委託 – 2013-02-20 19:16:01

1

從代碼它似乎你正在尋找一個代表,而不是參考一種方法。 (其實並不存在於C#中)

我會將字典更改爲Dictionary<string,Func<BattleActor,BattleActor> lookup 雖然這是個人偏好問題,與您的問題無關。 (您可以在下面的代碼SkillEffect替代Func<BattletActor,BattlActor>

,然後做

Func<BattleActor,BattleActor> func = (Func<BattleActor,BattleActor>) 
        Delegate.CreateDelegate(typeof(Func<BattleActor,BattleActor>), methodInfo); 

lookup.Add(methodInfo.Name,func); 

一個仿函數是一個委託,並且可以調用就像任何其他代表

lookup["mymethod"](actor,target); 

你可以看到this question欲瞭解更多信息

+0

他已經這樣做了,只有他明確地定義了代表代碼頂部而不是使用'Func':'委託void SkillEffect(BattleActor actor,BattleActor target);' – 2013-02-20 19:14:44

+0

@ChrisSinclair他沒有創建一個委託,這是關鍵。 – 2013-02-20 19:17:45

+0

是的,但爲什麼不利用他現有的代表,而不是將'Func '投入混合? – 2013-02-20 19:22:57

相關問題