后代可见的公共类成员

发布于 2024-07-23 05:07:59 字数 957 浏览 4 评论 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 的后代一起工作并获得相同的必须具有构建器语义?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

大姐,你呐 2024-07-30 05:08:00

剥皮的方法有很多,但阻力最小的方法是将各种部件类型的构造函数设为公共或内部。

There are many ways to skin a cat, but the path of least resistance here is going to be making the constructors of your various part types public or internal.

江挽川 2024-07-30 05:08:00

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

You can't do it, except for putting them in their own assembly and use the internal access specifier.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文