想象一下,原则上可以通过指定两个属性中的一个的值来创建一个类,这两个属性的类型恰好相同。下面的代码使用的named and optional parameters二者的结合构造区分完成此:使用命名参数和可选参数来区分构造函数
class Program
{
static void Main()
{
//Note: these 2 ctors are distinguished only by the argument naming convention:
thing thingWithMass = new thing(mass: 10);
thing thingWithVolume = new thing(vol: 25);
}
class thing
{
int Density = 3;
int Mass;
int Vol;
public thing(int mass)
{
Mass = mass;
Vol = Mass/Density;
}
// Note the use of the optional variable to distinguish this ctor:
public thing(int vol, bool isVol=true)
{
Vol = vol;
Mass = Vol * Density;
}
}
}
所以(有些奇怪)这个代码编译和完美的作品,但它是不好的形式?这看起来有点像诡计,我想知道是否有一种潜伏的危险对我来说并不明显?它有味道吗?
注:在这种特殊情况下,我认识到,我也只能做到基本相同的事情有一个构造函数,看起来像这样:
public thing(int mass=0, int vol=0) //plus a couple of if() statements in the body
但在我的实际情况有相当涉及其他一些参数,并将它们全部组合成一个构造函数会变得有点笨拙和难以阅读。
我会说它闻起来有点。任何使用这个课程的人都必须知道如何处理这个诡计,否则他们可能会收到意想不到的结果。 – JLRishe 2014-09-25 16:22:17
我认为这将是最好的显示你的真实代码,因为坦率地说,现在我想问你为什么甚至让一个类(一个引用类型btw)包装一个整数值。 – Crono 2014-09-25 17:26:43
@Crono:我的班远比这更复杂;对于这个例子我只是删除了一些不必要的东西来演示构造逻辑。 – kmote 2014-09-25 17:45:59