從另外一個調用一個構造函數 - Call one constructor from another

問題:

I have two constructors which feed values to readonly fields. 我有兩個構造函數,它們將值提供給只讀字段。 ide

public class Sample
{
    public Sample(string theIntAsString)
    {
        int i = int.Parse(theIntAsString);
        _intField = i;
    }

    public Sample(int theInt) => _intField = theInt;
    public int IntProperty    => _intField;

    private readonly int _intField;
}

One constructor receives the values directly, and the other does some calculation and obtains the values, then sets the fields. 一個構造函數直接接收值,另外一個構造函數進行一些計算並得到值,而後設置字段。 函數

Now here's the catch: 如今這是要抓住的地方: this

  1. I don't want to duplicate the setting code. 我不想重複設置代碼。 In this case, just one field is set but of course there may well be more than one. 在這種狀況下,只設置了一個字段,可是固然可能不止一個。
  2. To make the fields readonly, I need to set them from the constructor, so I can't "extract" the shared code to a utility function. 要使這些字段爲只讀,我須要從構造函數中進行設置,所以沒法將共享代碼「提取」到實用程序函數中。
  3. I don't know how to call one constructor from another. 我不知道如何從另外一個調用一個構造函數。

Any ideas? 有任何想法嗎? idea


解決方案:

參考一: https://stackoom.com/question/GovV/從另外一個調用一個構造函數
參考二: https://oldbug.net/q/GovV/Call-one-constructor-from-another
相關文章
相關標籤/搜索