为什么带有 ExpandoObject 参数的方法的推导 return 类型总是动态的?
Why the deduced return type of a method with a ExpandoObject parameter is always dynamic?
如下代码片段,为什么list
的推导类型在VS2017中是动态的?因此,这段代码会产生编译错误。我注意到,如果我将 dynamic
关键字更改为 var
,那么一切正常。
如果我想继续使用 dynamic
关键字,该如何解决?
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;
}
}
涉及声明为 dynamic
的参数的操作被推断为 return 动态本身。来自 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.
如果您想转换回非动态类型,只需按照您想要的方式声明变量即可。这有效:
List<string> list = GetList(d);
...并允许编译其余代码。
如下代码片段,为什么list
的推导类型在VS2017中是动态的?因此,这段代码会产生编译错误。我注意到,如果我将 dynamic
关键字更改为 var
,那么一切正常。
如果我想继续使用 dynamic
关键字,该如何解决?
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;
}
}
涉及声明为 dynamic
的参数的操作被推断为 return 动态本身。来自 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.
如果您想转换回非动态类型,只需按照您想要的方式声明变量即可。这有效:
List<string> list = GetList(d);
...并允许编译其余代码。