首页 > 解决方案 > 带有接口类型键的字典,获取实现接口的键

问题描述

我有一本interface类型字典和Func. (IBase是 和的基础IA)IBIC

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每种接口类型的语句。

标签: c#

解决方案


Type公开一个GetInterfaces()方法,该方法返回该类型实现的所有接口。

如果您的类型只实现一个接口,这可能会起作用,但如果实现了更多,您可能需要重新设计解决方案。也许一个工厂会为指定的接口类型返回一个映射器?

相关阅读:https ://docs.microsoft.com/en-us/dotnet/api/system.type.getinterfaces?view=netframework-4.7.2


推荐阅读