When passing dynamic to method, the result is dynamic expression, even if it is not

前端 未结 2 1176
轻奢々
轻奢々 2020-12-21 09:30

In C# 5 when I tried to pass a dynamic as a method parameter the result for some reason became dynamic.

class Program
{
    static void Main(string[] args)
          


        
相关标签:
2条回答
  • 2020-12-21 10:26

    dynamic is type unknown at compile time but in the runtime. So in the runtime it can be a string type and there could be a better match called Find(string value) which returns a different type. That's the reason the compiler is unable to tell you. It is resolved at runtime.

    0 讨论(0)
  • 2020-12-21 10:28

    Because there could be a Find that matches another method than your Find at runtime, once you go dynamic, everything is dynamic, including resolving which method fits, so as soon as something is dynamic in an expression, the whole expression is dynamic.

    For example there could be another method like

    public static T Find<T>(sometype value)
    {
       return default T;
    }
    

    This would be a better match at runtime if the dynamic was actually of type sometype, so as long as the compiler doesn't know what dynamic is it can't infer the return type since that type could be anything returned by the method that matches best AT RUNTIME.

    So the compiler says it returns dynamic because that's it best bet, your method returns something else, but the compiler doesn't know yet if that method will be the one called.

    0 讨论(0)
提交回复
热议问题