简体   繁体   English

空传播算子和动态变量

[英]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. 我一直在研究C#6中的零传播运算符,并尝试使用dynamic类型的变量,但没有成功。 Consider the code below, it compiles but CLR throws AccessViolationException at runtime when the null-propagation is applied to dynamic object. 考虑下面的代码,它会编译,但是当将null传播应用于动态对象时,CLR会在运行时抛出AccessViolationException

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. 起初我认为这可能是一个bug,但后来我想到了struct Normally you can't apply ?. 通常你不能申请?. operator to a value type variable (because it cannot be null). 运算符到值类型变量(因为它不能为null)。 But you can cast it to dynamic and then apply the operator. 但您可以将其强制转换为dynamic ,然后应用运算符。 So I changed SomeType to be struct and got the same exception. 所以我将SomeType更改为struct并得到了相同的异常。

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都非常丑陋,在运行代码时是否获得相同的内容?

AccessViolationException几乎总是编译器错误或格式错误的PInvoke调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM