简体   繁体   中英

dynamic keyword affects return type

I'm not entirley sure why the following code compiles

namespace ConsoleApp13
{
    public class Person
    {

    }
    class Program
    {
        static void Main(string[] args)
        {
            dynamic expand = new ExpandoObject();
            List<Person> people = GetPerson(expand);

        }

        public static Person GetPerson(int item)
        {
            return new Person();
        }

    }
}

Why does the dynamic keyword impact the return type. It's like the compiler give's up on type checking as soon as dynamic is introduced. Is this expected behavior?

Is this expected behavior?

Yes. Almost anything you do that involves a dynamic value ends up with a compile-time type of dynamic . Note that binding is performed dynamically, so even though in this specific case you've only got one GetPerson method, in the more general case of method invocation, overloads could be present at execution time that aren't present at compile-time, with different return types.

There are a few operations which don't end up with a dynamic type:

  • Casting (eg (string) dynamicValue )
  • The is operator (eg dynamicValue is string )
  • The as operator (eg dynamicValue as string
  • Constructor calls (eg new Foo(dynamicValue) )

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