想象一下,原則上可以通過指定兩個屬性中的一個的值來創建一個類,這兩個屬性的類型恰好相同。下面的代碼使用的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