开发者

In C#, is it possible for an object to have a data member that by default references itself?

开发者 https://www.devze.com 2023-02-04 20:46 出处:网络
I\'m trying to create an account s开发者_运维知识库ystem, where accounts have a \"primary account\" reference.The reference will indicate the primary account for this object.When created, I would like

I'm trying to create an account s开发者_运维知识库ystem, where accounts have a "primary account" reference. The reference will indicate the primary account for this object. When created, I would like it to, by default, be set to be it's own primary account.

Is this going to cause an error?

How exactly do I write that? Would it use the word this?

I'm newer to OOP, thank you for the help!


Maybe something like

public class Account
{
    private Account _parent;
    public Account Parent
    {
        get { return _parent ?? this; }
        set { _parent = value; }
    }
}

Would help?


Haven't tried this out, but something like this should work:

public class MyObject {
  protected MyObject myObjectInstance;
  public MyObject MyObjectInstance {
    get { return (myObjectInstance == null)? this: myObjectInstance;
    set { myObjectInstance = value; }
  }
}

This way you have a property called MyObjectInstance that does exactly what you want it to.


I think you would should be able to do this by writing your property like

private Account _primaryAccount;
public Account PrimaryAccount
{
    get
    {
        if(_primaryAccount == null)
            return this;
        return _primaryAccount;
    }
    set { _primaryAccount = value; }
}


It would probably be more correct to use the value null to indicate the Account instance has no parent.

Your account structure is a tree structure (one of the most common patterns in programming). In a tree structure, a node with no parent is considered a root element. In .NET, the clearest way for a node to say "I have no parent" is to return null from a "parent" property.

There is nothing directly wrong with having a property return the current instance as its value, but it is somewhat confusing and moves away from the conventions expected in a tree structure.

0

精彩评论

暂无评论...
验证码 换一张
取 消