所以我有一些代码在方法之间传递这个匿名对象:
var promo = new
{
Text = promo.Value,
StartDate = (startDate == null) ?
new Nullable<DateTime>() :
new Nullable<DateTime>(DateTime.Parse(startDate.Value)),
EndDate = (endDate == null) ?
new Nullable<DateTime>() :
new Nullable<DateTime>(DateTime.Parse(endDate.Value))
};
Run Code Online (Sandbox Code Playgroud)
接收此匿名对象类型的方法将其类型声明为dynamic:
private static bool IsPromoActive(dynamic promo)
{
return /* check StartDate, EndDate */
}
Run Code Online (Sandbox Code Playgroud)
在运行时,然而,如果StartDate或者EndDate被设定为new Nullable<DateTime>(DateTime.Parse(...)),接收到该方法dynamic的对象(命名promo)执行这样的:
if (promo.StartDate.HasValue && promo.StartDate > DateTime.Today ||
promo.EndDate.HasValue && promo.EndDate < DateTime.Today)
{
return;
}
Run Code Online (Sandbox Code Playgroud)
它引发了一个异常:
Server Error in '/' …Run Code Online (Sandbox Code Playgroud) 鉴于这个简短的示例程序:
static void Main(string[] args)
{
Console.WriteLine(Test("hello world"));
}
private static int Test(dynamic value)
{
var chars = Chars(value.ToString());
return chars.Count();
}
private static IEnumerable<char> Chars(string str)
{
return str.Distinct();
}
Run Code Online (Sandbox Code Playgroud)
运行时,它会产生类似于的异常:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''object' does not contain a definition for 'Count''
含义编译器选择dynamic作为首选类型的chars变量.
有没有理由不选择IEnumerable<char>具体类型,考虑动态不是从Chars方法返回的?只是手动更改类型以IEnumerable<char>解决问题,但我想知道为什么dynamic在这种情况下是默认值?
编辑
我可能使用了比必要更复杂的例子.似乎这里提出的问题是:
提供更简洁的示例和一些有关其工作方式的见解.
https://blogs.msdn.microsoft.com/ericlippert/2012/11/05/dynamic-contagion-part-one/
描述编译器如何处理动态.