下面的代码在执行这一行时会抛出异常(即 something.Add(name))。
我想在执行这个时捕获实际的异常。我的意思是我不想使用 catch(Exception ex) 而不是我想知道这里抛出的正确异常是什么。
try
{
dynamic name= "test";
var something = new List<decimal>();
something.Add(name);
}
catch(Exception ex)
{
throw ex;
}
提前致谢。
不知道您为什么要尝试将字符串转换为小数,但是好的...答案是 Microsoft.System.CSharp.RuntimeBinder.RuntimeBinderException。
来源:实际运行代码。:)
在大多数情况下,动态类型的行为类似于类型对象,它绕过了静态类型检查。在编译时,假定动态类型的元素支持任何操作。
[来源:MSDN-1、MSDN-2 ]
在你的情况下:
您可以尝试以下代码:
try
{
dynamic name= "test";
var something = new List<decimal>();
something.Add(name);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
Console.WriteLine(ex.Message);
}
动态类型示例:
using System;
class Program
{
static void Main(string[] args)
{
dynamic dynVar = 2;
Console.WriteLine(dynVar.GetType());
}
}
将输出为:
System.Int32
List<decimal> dl = new List<decimal>();
dl.Add("Hello");