Call one constructor from another

I have two constructors which feed values to readonly fields.

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;

}

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:

  • 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.
  • 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.
  • I don't know how to call one constructor from another.
  • Any ideas?


    喜欢这个:

    public Sample(string str) : this(int.Parse(str)) {
    }
    

    如果你不想在自己的方法中进行初始化(例如,因为你想在初始化代码之前做太多的事情,或者试着包装它,或者其他任何东西),你不能满意地实现你想要的东西,你可以拥有任何或所有的东西构造函数通过引用初始化例程来传递只读变量,然后可以随意操作它们。

    class Sample
    {
        private readonly int _intField;
        public int IntProperty
        {
            get { return _intField; }
        }
    
        void setupStuff(ref int intField, int newValue)
        {
            intField = newValue;
        }
    
        public Sample(string theIntAsString)
        {
            int i = int.Parse(theIntAsString);
            setupStuff(ref _intField,i);
        }
    
        public Sample(int theInt)
        {
            setupStuff(ref _intField, theInt);
        }
    }
    

    Before the body of the constructor, use either:

    : base (parameters)
    
    : this (parameters)
    

    Example:

    public class People: User
    {
       public People (int EmpID) : base (EmpID)
       {
          // Add more statements here.
       }
    }
    
    链接地址: http://www.djcxy.com/p/18012.html

    上一篇: 从python列表中删除坐标

    下一篇: 从另一个调用一个构造函数