Anonymous Type vs Dynamic Type

前端 未结 6 549
春和景丽
春和景丽 2020-11-30 21:30

What are the real differences between anonymous type(var) in c# 3.0 and dynamic type(dynamic) that is coming in c# 4.0?

6条回答
  •  余生分开走
    2020-11-30 21:52

    There's three times, with three actors - one in each time.

    • Design-time - programmer
    • Compile-time - c# compiler
    • Run-time - .net runtime

    Anonymous types are declared and named by the compiler. This declaration is based on the programmer's specification (how he used the type). Since these types are named after the programmer has left the process, they appear to be nameless to the programmer, hence "anonymous".

    • The programmer says: Some type has a Name and Address
    • The compiler says : There's a type named xyz with Name and Address properties and fields, both strings.
    • the runtime says : I can't tell any difference between xyz and any type that the programmer made.

    dynamic typing in c# allows you to call methods that may or may not exist at compile time. This is useful for calling into python or javascript, which are not compiled.

    • The programmer says: treat this instance of a car as a dynamic type. Now, quack.
    • The compiler says: dynamic typing eh? must be ok. I won't complain because I can't check it.
    • The runtime attempts to make the instance of car, quack.

提交回复
热议问题