Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...