相关疑难解决方法(0)

从另一个调用一个构造函数

我有两个构造函数,它们将值提供给只读字段.

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;
}
Run Code Online (Sandbox Code Playgroud)

一个构造函数直接接收值,另一个构造函数进行一些计算并获取值,然后设置字段.

现在这里是抓住:

  1. 我不想复制设置代码.在这种情况下,只设置一个字段,但当然可能不止一个.
  2. 要使字段只读,我需要从构造函数中设置它们,因此我无法将共享代码"提取"到实用程序函数中.
  3. 我不知道如何从另一个构建函数调用.

有任何想法吗?

c# constructor

927
推荐指数
8
解决办法
43万
查看次数

标签 统计

c# ×1

constructor ×1