How can I instantiate immutable mutually recursive objects?

后端 未结 4 1993
闹比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:07

    You can do it by adding a constructor overload that accepts a function, and passing the this reference to that function. Something like this:

    public sealed class Foo {
        private readonly object something;
        private readonly Foo other;
    
        public Foo(object something, Foo other) {
            this.something = something;
            this.other = other;
        }
    
        public Foo(object something, Func makeOther) {
            this.something = something;
            this.other = makeOther(this);
        }
    
        public object Something { get { return something; } }
        public Foo Other { get { return other; } }
    }
    
    static void Main(string[] args) {
        var foo = new Foo(1, x => new Foo(2, x)); //mutually recursive objects
        Console.WriteLine(foo.Something); //1
        Console.WriteLine(foo.Other.Something); //2
        Console.WriteLine(foo.Other.Other == foo); //True
        Console.ReadLine();
    }
    

提交回复
热议问题