簡體   English   中英

具有接口類型的鍵的字典,獲取實現接口的鍵

[英]Dictionary with a key of interface type, get keys where interface is implemented

我有interface類型和Func的字典。 IBaseIAIBIC

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()方法,該方法返回Type實現的所有接口。

如果您的類型僅實現一個接口,則可能會起作用,但是如果實現了更多的接口,則可能需要重新編寫解決方案。 也許工廠將為指定的接口類型返回一個映射器?

相關閱讀內容: https : //docs.microsoft.com/zh-cn/dotnet/api/system.type.getinterfaces?view=netframework-4.7.2

這將不起作用,因為字典類型與實例類型不匹配。

如果檢查字典,您會發現存儲為鍵的類型是接口的類型:

{Name = "IA" FullName = "SomeNameSpace.IA"}

因此,當您嘗試使用實例的類型獲取值時,沒有匹配項,並且失敗。

如果您希望此方法有效,則需要在字典中注冊實例的類型以進行適當的解析:

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)},
    //This would make it work
    {typeof(SomeInstanceType), p=> _mapper.Map(p as IA) }
};

這顯然不是很實用。

相反,您可以嘗試找出類型是否實現您的詞典所說明的接口之一:

var interfaces = theInstance.GetType().GetInterfaces();
var key = _dictionary.Keys.Where(k => interfaces.Contains(k)).FirstOrDefault();

if (key == null) 
    return Enumerable.Empty<IResult>();

var map= _dictionary[key];
var result = map(theInstance);
return result;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM