我得到一个RuntimeBinderException
与消息动态属性赋值抛出RuntimeBinderException
Cannot implicitly convert type 'object' to 'MyNamespace.SomeEnum?'. An explicit conversion exists (are you missing a cast?)
下面的代码生成错误:
public enum SomeEnum
{
Val1
}
public class Example
{
public SomeEnum? EnumMember { get; set; }
}
public static class Program
{
static void Main()
{
dynamic example = new Example();
// Works without issue
example.EnumMember = (dynamic)Enum.Parse(typeof(SomeEnum), "Val1");
// Works without issue
example.EnumMember = Enum.Parse(example.EnumMember.GetType(), "Val1");
// Throws the aforementioned RuntimeBinderException
example.EnumMember = Enum.Parse(typeof(SomeEnum), "Val1");
}
}
为什么到前两行的工作(包括返回类型动态) ,但第三个抛出异常(当返回类型是对象)?我的印象是,当分配给动态时,绑定是使用右侧的实际运行时类型来执行的。有人可以请我指出,为什么第三行无法按书面形式运行?
不是第二个例子'object'中的RHS的编译时类型,而不是'dynamic'?这就是我被卡住的地方 - 第二个和第三个调用与'typeof'的编译时解析不同。 –
@DStanley:没有,因为这个调用是动态绑定的,因为第一个参数使用'example'。尝试将结果分配给'var',并将鼠标悬停在声明上,然后您会看到:) –
@DStanley不,因为example.EnumMember.GetType()返回'dynamic',所以Enum.Parse表达式必须根据定义,也返回类型'dynamic'。 –