后代可见的公共类成员
作为另一个类的公共类成员,我从构建器模式中获得了很大的吸引力:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
剥皮的方法有很多,但阻力最小的方法是将各种部件类型的构造函数设为公共或内部。
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.
你不能这样做,除非将它们放入自己的程序集中并使用内部访问说明符。
You can't do it, except for putting them in their own assembly and use the internal access specifier.