如何确定标识符是否引用具有NULL值的内容

本文关键字:NULL 何确定 标识符 是否 引用 | 更新日期: 2023-09-27 17:55:01

我的应用程序由一对具有父/子关系的类组成,其中子类具有一个父对象成员,并且父类具有子对象成员的列表(对于我下面的简化示例,我只使用单个对象)。这些类的信息从数据库中获取,同时获得相应的父/子对象。当获得父对象导致它获得其子对象时,这就成为一个问题,导致所有子对象获得它们的父对象,导致…好吧,你懂的。

为了阻止这个循环,我在获取对象的方法中为任何相关对象使用可选参数。当其中一个对象想要获取其相对对象时,分配此参数。我想知道是否有可能检查"父"或"子"在下面的例子中是否引用了某些东西,尽管引用的对象为NULL。我认为这可以在c++中使用指针,但据我所知,c#是无指针的。(

class ParentClass
{
    ChildClass _child;
    public ParentClass(ChildClass child)
    {
        _child = child;
    }
}
class ChildClass
{
    ParentClass _parent;
    public ChildClass(ParentClass parent)
    {
        _parent = parent;
    }
}
public static class ItemGetter
{
    public static ChildClass GetChild(ParentClass parent = null)
    {
        ChildClass c = null;
        // Here I want to check if 'parent' is referencing anything, regardless of null value.
        ParentClass p = parent ?? GetParent(c);
        c = new ChildClass(p);
        return c;
    }
    public static ParentClass GetParent(ChildClass child = null)
    {
        ParentClass p = null;
        // Here I want to check if 'child' is referencing anything, regardless of null value.
        ChildClass c = child ?? GetChild(p);
        // References to itself as being the parent.
        p = new ParentClass(c);
        return p;
    }
}

如何确定标识符是否引用具有NULL值的内容

我认为你的第一个假设是不正确的:

当获取父对象的结果时,

就会出现问题获取它的子对象,导致所有子对象都获得它们的父对象,导致…好吧,你懂的。

这不是问题,因为在内存中只存在同一个对象的一个实例。你只能在父对象和子对象中引用对象;不是实物。因此,使用引用是安全的,即使它看起来像一个无限循环。

你需要获取父对象和它的子实体;你不需要做任何检查。