简体   繁体   English

如何调用空引用对象的属性

[英]how to invoke a Property of a null reference object

Consider the following class which contains a property Height 考虑以下包含属性Height的类

internal class TreeNode
{
  public int value;
  public TreeNode Left;
  public TreeNode Right;

  public int Height{get;private set}
}

a TreeNode type variable node is initialized (ie node==null returns false) and TreeNode.Left =null 初始化TreeNode类型的变量node (即node==null返回false),并且TreeNode.Left =null

Trying node.Left.Height will throw a NullRefrenceException, Is there any direct way so that i can access the property Height from a null reference object so that node.Left.Height returns -1. 尝试node.Left.Height将抛出NullRefrenceException,是否有任何直接方法可以让我从空引用对象访问属性Height,以便node.Left.Height返回-1。

I know one method is to use a function with a signature int getHeight(TreeNode node) where i can check the node for nullity. 我知道一种方法是使用带有签名int getHeight(TreeNode node)的函数,在该函数中我可以检查节点是否为空。 but i want to use node.Left.Height kind of expression to return the desired value. 但我想使用node.Left.Height类型的表达式返回所需的值。

You're asking how to get the height of an undefined object? 您在问如何获取未定义对象的高度? That is simply not possible. 那根本不可能。 Like you can't measure the height of an building if it is not there. 就像您无法测量建筑物的高度(如果不存在)。

Stick to the method based approach. 坚持基于方法的方法。 Or create a property in your class like this: 或者在您的课程中创建一个属性,如下所示:

public int LeftHeight 
{ 
    get 
    { 
        return Left == null ? -1 : Left.Height;
    }
}

You could implement properties for Left and Right that never return null. 您可以为Left和Right实现永远不返回null的属性。

private TreeNode _left;
private TreeNode _right;
public TreeNode Left
{
    get
    {
        return _left ?? new TreeNode() { Height = -1 };
    }
    set
    {
        _left = value;
    }
}
public TreeNode Right
{
    get
    {
        return _right ?? new TreeNode() { Height = -1 };
    }
    set
    {
        _right = value;
    }
}

Actually when u are dealing with c# 6 there is a null propagation operator. 实际上,当您处理c#6时,会有一个空传播运算符。

Sample: 样品:

int? length = text?.Length;

Null Propagation OPerator 空传播运算符

Some people have made similar suggestions, but you could do something like 有人提出了类似的建议,但您可以做类似的事情

text?.Length ?? -1

If text is null it'll give the default value -1. 如果text为null,则默认值为-1。 There is no way to "directly" do text.Length though - that wouldn't make sense because there is no object to get the length of . 有没有办法“直接”做text.Length虽然-这是没有意义的,因为没有对象获取长度。

As an analogy, if I were to ask you what the height of the unicorn living in Milwaukee, WI is, how would you answer? 打个比方,如果我要问你,威斯康星州密尔沃基市独角兽的身高是多少,你会如何回答? Clearly, there is no unicorn in Milwaukee, WI to get the height of, so there's no way to give a meaningful answer other than "there is no such unicorn." 显然在威斯康星州密尔沃基没有麒麟获得的高度,所以没有办法给出比其他有意义的回答“没有这样的独角兽。”

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

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