不可分配的词典

时间:2015-02-03 12:08:01

标签: c# .net dictionary

简单的问题。为什么这样的事情不可能?

private static readonly Dictionary<Func<MarketModel, string>, Func<Market, string>>
        MarketMappingDictionary = new Dictionary<Func<MarketModel, string>, Func<Market, string>>
        {
            {o => o.Name, o => o.Name},
            {o => o.CountryId, o => o.Country.Code},
            {o => o.CurrencyId, o => o.Currency.Code},
        };

private static readonly Dictionary<Func<ParnerModel, string>, Func<Pertner, string>>
       PartnerMappingDictionary = .....


private readonly Dictionary<Type, Dictionary<Func<object, string>, Func<object, string>>> 
        _objectMappingDictionary = new Dictionary<Type, Dictionary<Func<object, string>, Func<object, string>>>
    {
        {typeof (MarketModel), MarketMappingDictionary},
        {typeof (PartnerModel), PartnerMappingDictionary}

};

错误消息显示Dictionary<Func<MarketModel, string>, Func<Market, string>>  不能与Dictionary<Func<object, string>, Func<object, string>>

分配

1 个答案:

答案 0 :(得分:3)

这是不可能的,因为您无法将Dictionary<Func<MarketModel, string>, Func<MarketModel, string>>投射到Dictionary<Func<object, string>, Func<object, string>>

这些类型不是远程兼容的。如果允许,你可以这样做:

Func<object, string> f = o => o.ToString();

var d = new Dictionary<Func<MarketModel, string>, Func<MarketModel, string>>();

Dictionary<Func<object, string>, Func<object, string>> d2 = d;

d2[f] = f;

现在d将包含 a Func<MarketModel, string>的值。那将是一个大问题。