Anomaly when using 'var' and 'dynamic'

前端 未结 2 864
北荒
北荒 2020-12-25 11:32

I\'ve run into a bit on an Anomaly where for the first time ever, using the var keyword bit me.

Take this very simple method

public stat         


        
2条回答
  •  粉色の甜心
    2020-12-25 12:19

    Rick's answer is good, but just to summarize, you are running into the consequences of two basic design principles of the feature:

    1. if you ask for dynamic binding then you get dynamic binding.
    2. dynamic is just object wearing a funny hat.

    The first issue you identify is a consequence of the first design principle. You asked for analysis of the call to be deferred until runtime. The compiler did so. That includes deferring everything about the call until runtime, including overload resolution and determining the return type. The fact that the compiler has enough information to make a guess about what you meant is irrelevant.

    And if the compiler did make a guess about what you meant, then right now you'd be asking a different question, namely, "I made a tiny change to the set of methods available and suddenly the compiler changed its deduction of the type to dynamic, why?" It is very confusing to users when the compiler's behaviour is unpredictable.

    (All that said, there are a small number of situations in which the compiler will tell you that dynamic code is wrong. There are situations where we know that a dynamic binding will always fail at runtime, and we can tell you about them at compile time rather than waiting for your test case to fail.)

    The second issue you identify is a consequence of the second design principle. Because dynamic is just object wearing a funny hat, and because nullables box to either a null reference or a boxed non-nullable value type, there is no such thing as a "dynamic nullable".

提交回复
热议问题