class FirstSteps3
{
static void Main()//整数与整数相加 动态类型
{
dynamic items = new List<int> { 1, 2, 3 };
//items {System.Collections.Generic.List<int>}
dynamic valueToAdd = 2;
//valueToAdd 2
foreach (dynamic item in items)
//item 1 2 3
{
string result = item + valueToAdd;
//exception {"无法将类型“int”隐式转换为“string”"}
//System.Exception {Microsoft.CSharp.RuntimeBinder.RuntimeBinderException}
Console.WriteLine(result);
}
}
}
悲剧,试图将相加的结果转换为字符串。允许的唯一转换与C#中的常规语法一样,不会将int
转换成string。结果将产生异常。
除非很熟,否则开始使用动态类型时会频繁遭遇RuntimeBinderException。从某种程度上说,
它是一种新型的NullReferenceException。
输出
Exception: System.Reflection.TargetInvocationException: 调用的目标发生了异常。 ---> Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 无法将类型“int”隐式转换为“string”
在 CallSite.Target(Closure , CallSite , Object )
在 System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
在 Chapter14.FirstSteps3.Main() 位置 c:\FirstSteps3.cs:行号 16 位置是文件的位置
--- 内部异常堆栈跟踪的结尾 ---
在 System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
在 System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
在 System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
在 MiscUtil.ApplicationChooser.Run(Type type, String[] args)