Dictionary初始值设定项中的KeyValuePair类型推断

时间:2017-07-07 01:12:59

标签: c# dictionary namespaces .net-core type-inference

我正在使用密钥类型.container { position: fixed; left: 150px; top: 50px; .child { position: absolute; animation:mymove 1s infinite; &::before{ display: block; position: absolute; width: 25px; height: 25px; background-color: red; content: ""; right: 40px; animation: inherit; animation-delay: .15s; } div { width: 25px; height: 25px; background-color: red; animation: inherit; animation-delay: .30s; } &::after{ display: block; position: absolute; width: 25px; height: 25px; background-color: red; content: ""; left: 40px; bottom: 0px; animation: inherit; animation-delay: .45s; } } } @keyframes mymove { 0% { opacity: 1; } 100% { opacity: 0; } } 构建Dictionary。在KeyValuePair初始化程序中使用KeyValuePair.Create时,它不需要模板类型,并且正确推断了类型,以下内容正确编译,甚至没有警告:

Dictionary

现在重新组织了代码,类型private static readonly IDictionary<KeyValuePair<Market, MarketData>, string> channelDict = new Dictionary<KeyValuePair<Market, MarketData>, string> { { KeyValuePair.Create(Market.USD, MarketData.Trade), "trades" }, ... }; Market被移动到一个单独的项目和命名空间,命名空间由文件顶部的MarketData语句导入,但是现在相同的代码不会编译,它会引发这个错误:

using

我可以肯定error CS0305: Using the generic type 'KeyValuePair<TKey, TValue>' requires 2 type arguments 命名空间正确导入,因为简单的添加using没有产生任何错误,更重要的是,字典的定义:

private Market _m;

既没有产生错误,也是private static readonly IDictionary<KeyValuePair<Market, MarketData>, string> channelDict = new Dictionary<KeyValuePair<Market, MarketData>, string> 方法无法编译:

Create

那么为什么现在当类型参数在另一个命名空间中时它不能推断出类型,而它可以在之前呢?

1 个答案:

答案 0 :(得分:2)

在完成一些挖掘之后,我发现问题不在于KeyValuePair的初始化,而是因为目标框架的差异。

最初所有代码都在同一个.NET Core控制台应用程序中,将目标框架设置为netcoreapp2.0,并且从.NET Core 2.0中的文档中,KeyValuePair是一个静态类,带有静态方法Create,它将正确推断类型参数。

然后当我重新组织代码时,我将此部分移动到类库中,默认情况下,dotnet工具会将netstandard2.0设置为其目标框架,但KeyValuePairCreatenetstandard2.0中没有提供,正如您从docs看到的那样,它说:

  

当前选定的框架不支持此API。

这就是为什么代码在移动到库项目时无法编译的原因,netstandard框架中只有通用的KeyValuePair<K, V>版本。

作为一种解决方法,我验证了当我将.csproj文件中的目标框架设置为netcoreapp2.0outputtypelibrary时,它已成功编译。

OTOH,库项目默认使用netstandard,因为它确保库可以在不同的平台目标之间使用,因此更好的解决方法是不在库代码中使用static KeyValuePair.Create,而是使用通用版本:{{ 1}}。