c# - 带有接口类型键的字典,获取实现接口的键
问题描述
我有一本interface
类型字典和Func
. (IBase
是 和的基础IA
)IB
IC
var _dictionary =
new Dictionary<Type, Func<IBase, IEnumerable<IResult>>>
{
{typeof(IA), p => _mapper.Map(p as IA)},
{typeof(IB), p => _mapper.Map(p as IB)},
{typeof(IC), p => _mapper.Map(p as IC)}
};
IA
将(或等)的具体实例传递给IB
方法,我如何获得Func
与实例实现的匹配接口的对应:
public IEnumerable<IResult> Resolve(IBase theInstance)
{
// This fails because theInstance.GetType() result, is not the interface type
if (!_dictionary.TryGetValue(theInstance.GetType(), out var func)) return Enumerable.Empty<IResult>();
var result = func.Invoke(theInstance);
return result;
}
我试图避免使用switch
每种接口类型的语句。
解决方案
Type
公开一个GetInterfaces()
方法,该方法返回该类型实现的所有接口。
如果您的类型只实现一个接口,这可能会起作用,但如果实现了更多,您可能需要重新设计解决方案。也许一个工厂会为指定的接口类型返回一个映射器?
相关阅读:https ://docs.microsoft.com/en-us/dotnet/api/system.type.getinterfaces?view=netframework-4.7.2
推荐阅读
- python - 如何使用按钮将排序功能添加到 Matplotlib 条形图和线图
- reactive-programming - Spring webflux/reactor 使用@Scheduled 读取数据库并执行一些任务
- applescript - Apple 脚本遇到错误:如果您离开页面,“无法将缺失值输入到类型文档或选项卡中”
- python - 当 numpy select 满足两个或多个条件时如何添加首选项
- r - 如何操纵 RShiny Slider 的启发式方法以正确显示小范围而没有重复的中间标签?
- javascript - 使用 JS 是否可以检测 new Image().src 何时将其引用的图像加载到内存中?
- javascript - 隐藏输入按钮上的 .click() 不起作用(未定义)
- c# - 在扩展多个导航属性时避免 Microsoft OData 中的笛卡尔积
- javascript - React-modal 未在 iPhone 上打开
- perl - 如何在 Perl 中指定 WE8MSWIN1252 编码?