您好,有人可以解释一下一个对象如何通过NULL
守卫,然后在尝试访问不可为空的字段时引发异常吗? (布尔)
您可以在上方方法中看到类型为response
的对象Node
不为空。请注意boolean
字段IsArray
!!
让我们看看当我们的response
输入Deserialize
方法时会发生什么:
Passes null guard !!
然后在Null Reference Exception
上以non-nullable field
崩溃。正是在我说过要重点关注的字段上:boolean
IsArray
。
堆栈跟踪
{System.NullReferenceException: Object reference not set to an instance of an object.
at redius.Node.get_Kind() in D:\Work\redius\core\redius\Internals\Resp\Node.cs:line 15
at redius.Node.get_IsArray() in D:\Work\redius\core\redius\Internals\Resp\Node.cs:line 22
at redius.Deserializer.List.Deserialize(Node node) in D:\Work\redius\core\redius\Internals\Formatter\Deserializer\Deserializer.List.cs:line 19}
有人可以解释一下这怎么可能吗?下面是Node
类型:
public abstract partial class Node : IEquatable<Node> {
public enum Discriminator {
String,
Integer,
Array
}
public Discriminator Kind => this.NodeKind;
protected abstract Discriminator NodeKind { get; }
public Node.Array AsArray => this as Node.Array;
public Node.Integer AsInteger => this as Node.Integer;
public Node.String AsString => this as String;
public bool IsArray => this.Kind == Discriminator.Array;
public bool IsString => this.Kind == Discriminator.Integer;
public bool IsInteger => this.Kind == Discriminator.String;
#region IRAW
protected virtual ReadOnlyMemory<byte> GetRaw() {
return new byte[] { };
}
#endregion
public bool Equals(Node other) {
if (this.Kind != other.Kind) {
return false;
}
bool result;
switch (other.Kind) {
case Discriminator.Array: result = this.AsArray.Equals(other.AsArray); break;
case Discriminator.Integer: result = this.AsInteger.Equals(other.AsInteger); break;
case Discriminator.String: result = this.AsString.Equals(other.AsString); break;
default: throw new NotImplementedException();
}
return result;
}
}
PS::当Node
进入Deserialize
方法时,调试器出现问题,因为我无法访问它(无法访问其字段)!>
PS 2 如果我尝试在Deserializer
方法中添加以下行:
var values = node.GetType().GetFields().Select(x => x.GetValue(node));
应用程序进入中断状态,并且出现以下异常:
System Execution Engine Exception