简体   繁体   中英

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

Below is the exact code I am running. Why does the compiler return dynamic and not type MyClass ?

My project is running on .NET Framework 4.7.2, but I configured it to use latest C# by adding public static class IsExternalInit { } and

<PropertyGroup>
    <LangVersion>latest</LangVersion>
</PropertyGroup>

My code:

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(""));
    }
}

在此处输入图像描述

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

The question presupposes a falsehood. The compiler's behaviour is correct, so asking why it should do an incorrect thing makes it hard to answer your question.

Instead I'll answer the question "what section of the specification determines when the compiler should classify an invocation as dynamic?"


I refer you to section 11.7.8.1 of the specification, which states:

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

An invocation_expression is dynamically bound (§11.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.

data is "at least one argument" that has type dynamic , so there you go.

In your specific case, the section on additional error checks applies -- but this section does not affect the classification of the invocation's type.

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


If your "why" question was not answered by a reference to the specification, then I'd encourage you to reformulate it as a "what" question. It's hard to know when a "why" question has been answered satisfactorily.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM