问题描述
我一直在研究C#6中的null传播运算符,并试图使其与 dynamic
类型的变量一起使用,但没有成功.考虑下面的代码,它可以编译,但是当将空传播应用于动态对象时,CLR在运行时抛出 AccessViolationException
.
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();
}
}
起初我以为这可能是一个错误,但是后来我想到了 struct
s.通常,您不能将?.
运算符应用于值类型变量(因为它不能为null).但是您可以将其强制转换为 dynamic
,然后应用运算符.因此,我将 SomeType
更改为 struct
,并得到了相同的异常.
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?
AccessViolationException
还是很丑陋,运行代码时是否得到相同的代码?
The AccessViolationException
is pretty ugly anyway, do you get the same one when you run the code?
推荐答案
AccessViolationException几乎总是编译器错误或格式不正确的PInvoke调用.
AccessViolationException is almost always either a compiler bug or a mal-formed PInvoke call.
这篇关于空传播算子和动态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!