tutorial - default constructor c#
從另一個調用一個構造函數 (5)
我有兩個構造函數將值提供給只讀字段。
class Sample
{
public Sample(string theIntAsString)
{
int i = int.Parse(theIntAsString);
_intField = i;
}
public Sample(int theInt)
{
_intField = theInt;
}
public int IntProperty
{
get { return _intField; }
}
private readonly int _intField;
}
一個構造函數直接接收值,另一個做一些計算並獲取值,然後設置字段。
這裡有一個問題:
- 我不想複製設置代碼。 在這種情況下,只設置一個字段,但當然可能有多個字段。
- 為了使字段只讀,我需要從構造函數中設置它們,所以我不能將共享代碼“提取”到實用程序函數。
- 我不知道如何從另一個構造函數中調用一個構造函數。
有任何想法嗎?
喜歡這個:
public Sample(string str) : this(int.Parse(str)) {
}
在構造函數的主體之前,請使用以下任一項:
: base (parameters)
: this (parameters)
例:
public class People: User
{
public People (int EmpID) : base (EmpID)
{
// Add more statements here.
}
}
我正在改進supercat的答案。 我猜也可以做到以下幾點:
class Sample
{
private readonly int _intField;
public int IntProperty
{
get { return _intField; }
}
void setupStuff(ref int intField, int newValue)
{
//Do some stuff here based upon the necessary initialized variables.
intField = newValue;
}
public Sample(string theIntAsString, bool? doStuff = true)
{
//Initialization of some necessary variables.
//==========================================
int i = int.Parse(theIntAsString);
// ................
// .......................
//==========================================
if (!doStuff.HasValue || doStuff.Value == true)
setupStuff(ref _intField,i);
}
public Sample(int theInt): this(theInt, false) //"false" param to avoid setupStuff() being called two times
{
setupStuff(ref _intField, theInt);
}
}
是的,你可以在呼叫基地或這個之前撥打其他方法!
public class MyException : Exception
{
public MyException(int number) : base(ConvertToString(number))
{
}
private static string ConvertToString(int number)
{
return number.toString()
}
}
這是一個調用另一個構造函數的例子,然後檢查它設置的屬性。
public SomeClass(int i)
{
I = i;
}
public SomeClass(SomeOtherClass soc)
: this(soc.J)
{
if (I==0)
{
I = DoSomethingHere();
}
}