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

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

    +1 on "No".

    Here's an alternative to the anonymous object way:

    var instance = MyClass.FactoryCreate(
        SomeProperty => "Some value",
        OtherProperty => "Other value");
    

    In this case FactoryCreate() would be something like:

    public static MyClass FactoryCreate(params Func[] initializers)
    {
        var result = new MyClass();
        foreach (var init in initializers) 
        {
            var name = init.Method.GetParameters()[0].Name;
            var value = init(null);
            typeof(MyClass)
                .GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase)
                .SetValue(result, value, null);
        }
        return result;
    }
    

提交回复
热议问题