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

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

    You can use an extension method such as the following:

    namespace Utility.Extensions
    {
        public static class Generic
        {
            /// 
            /// Initialize instance.
            /// 
            public static T Initialize(this T instance, Action initializer)
            {
                initializer(instance);
                return instance;
            }
        }
    }
    

    You would call it as follows:

    using Utility.Extensions;
    // ...
    var result = MyClass.FactoryCreate()
                    .Initialize(x =>
                    {
                        x.someProperty = someValue;
                        x.someProperty2 = someValue2;
                    });
    

提交回复
热议问题