Null propagation operator and dynamic variable

I have been looking at the null-propagation operator in C#6 and tried to make it work with the variables of dynamic type but without success. Consider the code below, it compiles but CLR throws AccessViolationException at runtime when the null-propagation is applied to dynamic object.

class SomeType
{
    public object SomeProperty { get; set; }

    static void Main()
    {
        var obj = new SomeType() { SomeProperty = "ABCD" };

        var p1 = ((dynamic)obj).SomeProperty;   //OK, p1 is set to "ABCD"
        var p2 = ((dynamic)obj)?.SomeProperty;  //AccessViolationException

        Console.ReadLine();
    }
}

At first I thought that this might be a bug but then I thought about struct s. Normally you can't apply ?. operator to a value type variable (because it cannot be null). But you can cast it to dynamic and then apply the operator. So I changed SomeType to be struct and got the same exception.

The question is, it is by design that null-propagation for dynamic variables always is going to throw exception because the underlying object may be a value type?

The AccessViolationException is pretty ugly anyway, do you get the same one when you run the code?


AccessViolationException几乎总是编译器错误或形式不正确的PInvoke调用。

链接地址: http://www.djcxy.com/p/75158.html

上一篇: Xamarin Studio c#空传播运算符

下一篇: 空传播算子和动态变量