【发布时间】:2020-09-07 20:56:47
【问题描述】:
最近,我遇到了一个关于使用dynamic w 的有趣问题。
当我将dynamic 对象作为参数传递时,无法推断该方法的返回类型。
这是最小的可重现示例:
这段代码编译成功:
class Program
{
public static void Main()
{
dynamic data = new { SomeProperty = "ABC" };
string response = IsTrue(data);
if (response == "1")
{
Console.WriteLine("How can this compile?");
}
}
private static bool IsTrue(object someData)
{
return true;
}
}
在上面的代码中,IsTrue 返回一个bool,但response 的类型不会被推断为bool。结果,上述代码编译成功。
在运行应用程序时,我得到以下运行时异常:
未处理的异常。 Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:运算符“==”不能应用于“布尔”和“字符串”类型的操作数 在 CallSite.Target(闭包,CallSite,对象,字符串) 在 System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,Tret](CallSite 站点,T0 arg0,T1 arg1)
这怎么可能?
【问题讨论】:
-
有趣,我得到了一个不同的异常:System.Linq.Expressions.dll 中发生了“Microsoft.CSharp.RuntimeBinder.RuntimeBinderException”类型的未处理异常无法将类型“bool”隐式转换为'字符串'.
标签: c#