Limitations of the dynamic type in C#

前端 未结 3 894
悲&欢浪女
悲&欢浪女 2020-12-19 12:09

Could you give me some reasons for limitations of the dynamic type in C#? I read about them in \"Pro C# 2010 and the .NET 4 platform\". Here is an excerpt (if quoting books

3条回答
  •  青春惊慌失措
    2020-12-19 12:51

    Eric (and Tomas) says it well, but here is how I think of it.

    This C# statement

    a.Method(arg => Console.WriteLine(arg)); 
    

    has no meaning without a lot of context. Lambda expressions themselves have no types, rather they are convertible to delegate (or Expression) types. So the only way to gather the meaning is to provide some context which forces the lambda to be converted to a specific delegate type. That context is typically (as in this example) overload resolution; given the type of a, and the available overloads Method on that type (including extension members), we can possibly place some context that gives the lambda meaning.

    Without that context to produce the meaning, you end up having to bundle up all kinds of information about the lambda in the hopes of somehow binding the unknowns at runtime. (What IL could you possibly generate?)

    In vast contrast, one you put a specific delegate type there,

    a.Method(new Action(arg => Console.WriteLine(arg))); 
    

    Kazam! Things just got easy. No matter what code is inside the lambda, we now know exactly what type it has, which means we can compile IL just as we would any method body (we now know, for example, which of the many overloads of Console.WriteLine we're calling). And that code has one specific type (Action), which means it is easy for the runtime binder to see if a has a Method that takes that type of argument.

    In C#, a naked lambda is almost meaningless. C# lambdas need static context to give them meaning and rule out ambiguities that arise from many possible coercisons and overloads. A typical program provides this context with ease, but the dynamic case lacks this important context.

提交回复
热议问题