词典与委托作为价值 [英] Dictionary with delegate as value
本文介绍了词典与委托作为价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下类
公共类CVisitor:IVisitor
{
公众诠释访问(心跳元)
{
Trace.WriteLine(心跳);
返回1;
}
公众诠释访问(信息元素)
{
Trace.WriteLine(信息);
返回1;
}
}
我想有一个词典与映射,每一个参数类型将被映射到它的实现功能:心跳会被映射到公众诠释访问(心跳元)
我觉得像做以下操作:
_messageMapper =新字典<类型,应该是什么吗? >();
_messageMapper.Add(typeof运算(心跳),我怎么把它放在这儿?);
我应该怎么放,而不是应该是什么吗?和我怎么把它放在这儿?
感谢
解决方案
新字典<类型,函数功能<对象,INT>>();
VAR cVisitor =新CVisitor();
_messageMapper.Add(typeof运算(心跳),
新的函数功能:LT;对象,INT>(心率=> cVisitor.Visit((心跳)心跳))
);
I have following class
public class CVisitor : IVisitor
{
public int Visit(Heartbeat element)
{
Trace.WriteLine("Heartbeat");
return 1;
}
public int Visit(Information element)
{
Trace.WriteLine("Information");
return 1;
}
}
I want to have a Dictionary with mappings, that every argument type will be mapped to it's implementation function:Heartbeat will be mapped to public int Visit(Heartbeat element)
I thought to do something like following:
_messageMapper = new Dictionary<Type, "what should be here ?" >();
_messageMapper.Add(typeof(Heartbeat), "and how I put it here?" );
what should I put instead "what should be here ?" and "and how I put it here?"
Thanks
解决方案
new Dictionary<Type, Func<object, int>>();
var cVisitor = new CVisitor();
_messageMapper.Add(typeof(Heartbeat),
new Func<object, int>(heartbeat => cVisitor.Visit((Heartbeat)heartbeat))
);
这篇关于词典与委托作为价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文