Why the deduced return type of a method with a ExpandoObject parameter is always dynamic?

牧云@^-^@ 提交于 2021-02-11 15:22:15

问题


As code snippet below, why the deduced type of list is dynamic in VS2017? Thus, this code will produce compile error. And I notice that if I change the dynamic keyword to var, then everything is OK.

How to fix it if I want to keep using dynamic keyword?

class Program
{
    static void Main(string[] args)
    {
        dynamic d = new ExpandoObject();
        var list = GetList(d); // ===> vs deduced list as dynamic
        var r = list.Select(x => x.Replace("a", "_"));
        var slist = new List<string>();
        var sr = slist.Select(x => x.Replace("a", "_"));
        Console.WriteLine(r.Count());
    }

    static List<string> GetList(ExpandoObject obj)
    {
        List<string> list = new List<string>() { "abc", "def" };
        return list;
    }
}

回答1:


Operations involving an argument declared as dynamic are inferred to return dynamics themselves. From the c# reference:

The result of most dynamic operations is itself dynamic. Operations in which the result is not dynamic include: (1) Conversions from dynamic to another type (2) Constructor calls that include arguments of type dynamic.

If you want to convert back to a non-dynamic type, just declare the variable the way you want it. This works:

List<string> list = GetList(d);

...and will allow the rest of your code to compile.



来源:https://stackoverflow.com/questions/54019029/why-the-deduced-return-type-of-a-method-with-a-expandoobject-parameter-is-always

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