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

前端 未结 7 1636
离开以前
离开以前 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:31

    Like everyone said, no.

    A lambda as an argument has already been suggested.
    A more elegant approach would be to accept an anonymous and set the properties according to the object. i.e.

    MyClass instance = MyClass.FactoryCreate(new {
        SomeProperty = someValue,
        OtherProperty = otherValue
    });
    

    That would be much slower though, since the object would have to be reflected on for all the properties.

提交回复
热议问题