0

作为另一个类的公共类成员,我从构建器模式中获得了很大的吸引力:

public class Part
{
    public class Builder
    {
        public string Name { get; set; }
        public int Type { get; set; }

        public Part Build()
        {
            return new Part(Name, Type);
        }
    }

    protected Part(string name, int type)
    {
        ...
    }
}

注意受保护的构造函数 - 我喜欢我必须使用生成器来获取零件的方式。来电

Part p = new Part.Builder() { Name = "one", Type = 1 }.Build();

工作得很好。我想做的是使用这个构建器来提供基于类型的特殊部件(例如):

public class SpecialPart : Part
{
    protected SpecialPart(string name, int type) : base(name, type) { }
}

并对构建器进行了轻微更改:

public Part Build()
{
    if (Type == _some_number_)
        return new SpecialPart(Name, Type);
    return new Part(Name, Type);
}

但这不起作用 - Part.Builder 看不到 SpecialPart 的受保护构造函数。如何让 Builder 使用 Part 的后代并获得相同的 must-have-a-builder 语义?

4

2 回答 2

2

给猫剥皮的方法有很多,但这里阻力最小的方法是让你的各种部件类型的构造函数公开或内部。

于 2009-06-02T19:14:05.857 回答
2

您不能这样做,除非将它们放在自己的程序集中并使用内部访问说明符。

于 2009-06-02T19:14:22.110 回答