gpt4 book ai didi

c# - 为什么编译器在应该返回特定类型时返回 `dynamic`?

转载 作者:行者123 更新时间:2023-12-05 09:25:48 25 4
gpt4 key购买 nike

下面是我正在运行的确切代码。为什么编译器返回 dynamic 而不是类型 MyClass

我的项目在 .NET Framework 4.7.2 上运行,但我通过添加 public static class IsExternalInit { }

将其配置为使用最新的 C#
<PropertyGroup>
<LangVersion>latest</LangVersion>
</PropertyGroup>

我的代码:

internal class Program
{
class MyClass
{
}

static class MyParser
{
public static MyClass Parse(dynamic data)
{
return new MyClass();
}
}

static void Do(dynamic data)
{
var parsedObj = MyParser.Parse(data);
...
}

static void Main(string[] args)
{
Do(JsonConvert.DeserializeObject(""));
}
}

enter image description here

最佳答案

Why does compiler return dynamic when it should return a specific type?

这个问题预设了一个谎言。编译器的行为是正确的,所以如果问它为什么应该做不正确的事情,就很难回答您的问题。

相反,我将回答“规范的哪一部分决定编译器何时应将调用分类为动态调用?”这个问题


请参阅规范的第 11.7.8.1 节,其中指出:

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#11781-general

An invocation_expression is dynamically bound (§11.3.3) if at leastone 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 avalue of type dynamic.

data 是类型为 dynamic 的“至少一个参数”,所以你去吧。

在您的特定情况下,有关附加错误检查的部分适用——但该部分不影响调用类型的分类。

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#1165-compile-time-checking-of-dynamic-member-invocation


如果您的“为什么”问题没有通过引用规范来回答,那么我鼓励您将其重新表述为“什么”问题。 It's hard to know when a "why" question has been answered satisfactorily.

关于c# - 为什么编译器在应该返回特定类型时返回 `dynamic`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75051916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com