Is it possible to use a c# object initializer with a factory method?

前端 未结 7 1603
离开以前
离开以前 2020-12-25 13:06

I have a class with a static factory method on it. I want to call the factory to retrieve an instance of the class, and then do additional initialization, preferablly via c#

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-25 13:22

    Yes. You can use object initializer for already created instance with the following trick. You should create a simple object wrapper:

    public struct ObjectIniter
    {
        public ObjectIniter(TObject obj)
        {
            Obj = obj;
        }
    
        public TObject Obj { get; }
    }
    

    And now you can use it like this to initialize your objects:

    new ObjectIniter(existingInstance)
    {
        Obj =
        {
            //Object initializer of MyClass:
            Property1 = value1,
            Property2 = value2,
            //...
        }
    };
    

    P.S. Related discussion in dotnet repository: https://github.com/dotnet/csharplang/issues/803

提交回复
热议问题