How can I instantiate immutable mutually recursive objects?

后端 未结 4 2005
闹比i
闹比i 2020-12-30 02:25

I have an immutable recursive type:

public sealed class Foo
{
    private readonly object something;
    private readonly Foo other; // might be null

    pu         


        
4条回答
  •  没有蜡笔的小新
    2020-12-30 03:11

    Below is an example of a class Foo with write-once immutability rather than popsicle immunity. A bit ugly, but pretty simple. This is a proof-of-concept; you will need to tweak this to fit your needs.

    public sealed class Foo
    {
        private readonly string something;
        private readonly Foo other; // might be null
    
        public Foo(string s)
        {
            something = s;
            other = null;
        }
    
        public Foo(string s, Foo a)
        {
            something = s;
            other = a;
        }
        public Foo(string s, string s2)
        {
            something = s;
            other = new Foo(s2, this);
        }
    }
    

    Usage:

    static void Main(string[] args)
    {
        Foo xy = new Foo("a", "b");
        //Foo other = xy.GetOther(); //Some mechanism you use to get the 2nd object
    }
    

    Consider making the constructors private and creating a factory to produce Foo pairs, as this is rather ugly as written and forces you to provide public access to other.

提交回复
热议问题