简体   繁体   中英

How do you determine whether an identifier is referencing something with a NULL value?

My application consists of pairs of classes that have parent/child relationships in the way that the child class has one parent object member , and the parent class has a list of child objects member (for my simplified example below I am only using single objects however). The information for these classes is fetched from the database, getting the respective parent/child objects simultaneously. This becomes a problem when getting the parent object results in it getting its child objects, resulting in all the child objects getting their parent objects, resulting in.. well, you get the idea.

To hinder this loop I am using an optional parameter for any related object in the method that fetches an object. This parameter is assigned when one of the objects wants to fetch its relative. I want to know if it is possible to check if "parent" or "child" in my example below are referencing something, despite the referenced object being NULL . I assume this would work with pointers in C++, but C# is pointerless as far as I know. :(

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;
    }
}

I think your first assumption is not proper:

This becomes a problem when getting the parent object results in it getting its child objects, resulting in all the child objects getting their parent objects, resulting in.. well, you get the idea.

It will not be problem, since in memory only one instance of the same object will exist. You will only have references of objects in parent object and child objects; not the actual objects. So it is safe to have references even it seems like an infinite loop.

you need to fetch a parent object with it's child entities; you do not need to make any checks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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