在.NET框架中,我經常看到構造函數被靜態函數替換爲構造新對象的成語。靜態構造方法vs構造函數
例如與BigInteger的有沒有構造函數取一個字符串,所以這是不可能的:
BigInteger i = new BigInteger("1000000103453543897");
但有一個靜態解析功能。
BigInteger i = BigInteger.Parse("1000000103453543897");
爲什麼這樣的類設計經常被選中?
我能想到的唯一的一件事就是創建一個對象,然後拋棄。這是真的,這是主要原因嗎?或者還有其他原因?
BigInteger(string value)
{
BigInteger result = new BigInteger(); // this one just returned in a Parse function
// compute bigint
// copy result to this
data = new uint[maxLength];
for (int i = 0; i < result.Length; i++)
data[i] = result.data[i];
Length = result.dataLength;
}
我認爲構造函數的隱含語義非常清晰:根據給定的參數以某種方式創建給定類型的值。這當然不包括使用參數來執行WriteLine()。雖然'Parse()'更清晰,因爲它解釋了參數實際意味着什麼。 – svick