简体   繁体   中英

public class member visible to descendents

I have been getting a lot of traction from a builder pattern as a public class member of another class:

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)
    {
        ...
    }
}

Note protected constructor - I like how I HAVE to use the builder to get a Part. Calls to

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

work great. What I would like to do is use this builder to serve up a special kind of part based on the Type (for example):

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

And a slight change to the builder:

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

But this doesn't work - Part.Builder can't see SpecialPart's protected constructor. How can I get Builder to work with descendents of Part and get the same must-have-a-builder semantics?

有很多方法可以给猫皮剥皮,但是这里阻力最小的途径将是使各种零件类型的构造函数成为公共的或内部的。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM