2012-07-16 87 views
7

我有以下類詞典與委託作爲價值

public class CVisitor : IVisitor 
    { 
     public int Visit(Heartbeat element) 
     { 
      Trace.WriteLine("Heartbeat"); 
      return 1; 
     } 
     public int Visit(Information element) 
     { 
      Trace.WriteLine("Information"); 
      return 1; 
     } 

    } 

我想和映射字典,每一個參數類型將被映射到它的實現功能:心跳將被映射到public int Visit(Heartbeat element)

我想要做的事情如下:

_messageMapper = new Dictionary<Type, "what should be here ?" >(); 
    _messageMapper.Add(typeof(Heartbeat), "and how I put it here?"); 

我應該把什麼,而不是「應該在這裏?」和「我怎麼把它放在這裏?」

感謝

+1

請問你的方法看起來(即是他們的定義相似?) – 2012-07-16 12:06:07

+0

也許,你可以創建你的方法爲代表,並在你的字典你TValue將System.Delegate ..你嘗試過嗎? – 2012-07-16 12:11:51

+0

@Yet另一個極客,訪客函數有完全不同的實現,它們是DTO映射器 – 2012-07-16 12:12:18

回答

7
new Dictionary<Type, Func<object, int>>(); 

var cVisitor = new CVisitor(); 
_messageMapper.Add(typeof(Heartbeat), 
    new Func<object, int>(heartbeat => cVisitor.Visit((Heartbeat)heartbeat)) 
); 
+0

爲什麼你使用Action?我有一個返回值 – 2012-07-16 12:15:03

+0

如果cVisitor是CVisitor的實例我如何使用新的Func (心跳=>(cVisitor.Visit(心跳))註冊 – 2012-07-16 12:24:22

+1

@NightWalker檢查當前變體 – 2012-07-16 12:29:06

2

你知道ActionFunc對象?看起來像你在找什麼。

var d = new Dictionary<Type, Action>(); 
d.Add(typeof(HeartBeat),()=>Trace.WriteLine("todum todum")); 

PS:THX YAG

+1

如果你想這樣做,那麼它應該是'Action'而不是'Action ',因爲沒有給出字符串輸入 – 2012-07-16 12:09:13

0

你最好在這裏調用的是使用反射。
1.使用typeof(Visitor).GetMethods()獲取訪問者類的所有方法(或稱爲「訪問」的所有方法?)。
2. GetMethods返回一個IEnumerable的MethodInfo。 GetParameters將爲您提供每個方法的參數。
3.所以,現在你可以建立你的(類型,MethodInfo)Dictionnary
4.使用Invoke調用Method。

Rq:使用反射的一個優點是,如果添加新方法,則該詞典仍然是最新的。沒有忘記添加方法的風險。