Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...