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

爱⌒轻易说出口 提交于 2020-01-10 05:40:06

问题


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)
    {
        dynamic value = "John";
        Find<int>(value).ToList();
    }

    public static IEnumerable<T> Find<T>(object value)
    {
        //SOME LOGIC
        yield return default(T); //REAL RESULT
    }
}

Find<T>(value) has to return IEnumerable<T>. Why compiler thinks it is dynamic?
I know that Find<int>(val as object).ToList(); solves this, but I want to understand WHY it happens.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/25665111/when-passing-dynamic-to-method-the-result-is-dynamic-expression-even-if-it-is

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!