问题
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