为什么我必须显式键入局部变量?

Why do I have to explicitly type a local variable?

在此示例中,我必须将变量显式声明为 IDictionary 而不是 var,但我不明白为什么。

有人可以解释为什么当我最初将其声明为 var 时 Visual Studio 工具提示指示它是 dynamic 即使 DictionaryHelper.ParseOptional() returns IDictionary<字符串,字符串>?

ParseOptional 声明为:

public static IDictionary<string, string> ParseOptional(dynamic json, string variableName);

mergeVariables 参数来自 Json.Decode(),因此是动态变量。

我正在使用 Visual Studio 2019,.NET v4.7.2,C#7.3,以防相关。

private static ICollection<IMergeVariable> ParseMergeVariables(dynamic mergeVariables)
{
    IDictionary<string, string> mergeDictionary = DictionaryHelper.ParseOptional(mergeVariables, "mergeVariables");

    return mergeDictionary?.Select(variable => new MergeVariable(variable.Key, variable.Value)).Cast<IMergeVariable>().ToList();
}

来自Microsoft Docs

The result of most dynamic operations is itself dynamic.

我相信这是因为类型是在运行时解析的(因此是“动态”类型)。

相关:

  • Why does a method invocation expression have type dynamic even when there is only one possible return type?
  • C# intellisense incorrect for method that takes a dynamic argument

编辑:我相信这种情况包含在 ECMA-334 C# Language Specification 5th Edition (December 2017) 的第 12.7.6 节调用表达式,第 12.7.6.1 小节的一般性中,其中指出:

An invocation-expression is dynamically bound (§12.3.3) if at least one of the following holds:

•The primary-expression has compile-time type dynamic.

•At least one argument of the optional argument-list has compile-time type dynamic

In this case, the compiler classifies the invocation-expression as a value of type dynamic.