在.NET框架中,我经常看到一种用静态函数替换构造函数的惯用语法,以创建一个新对象。
例如,在BigInteger中没有接受字符串参数的构造函数,因此无法使用以下方法:
BigInteger i = new BigInteger("1000000103453543897");
但是有一个静态的Parse函数。
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;
}
new int()
,所以它看起来像int
有一个构造函数。(虽然它实际上不是一个构造函数,它只是将值类型初始化为其默认值。) - svick