首页 文章

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

提问于
浏览
808

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

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;

}

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

现在这里是 grab :

  • 我不想复制设置代码 . 在这种情况下,只设置一个字段,但当然可能不止一个 .

  • 要使字段只读,我需要从构造函数中设置它们,所以我不能"extract"实用函数的共享代码 .

  • 我不知道如何从另一个构建函数调用 .

有任何想法吗?

8 回答

  • 4

    如果没有在自己的方法中进行初始化(例如因为你想在初始化代码之前做太多,或者将它包装在try-finally中,或者其他什么),那么你想要的东西不能令人满意地实现你可以拥有任何或所有构造函数通过引用初始化例程传递readonly变量,然后初始化例程将能够随意操作它们 .

    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);
        }
    }
    
  • 1359

    在构造函数的主体之前,使用以下任一方法:

    : base (parameters)
    
    : this (parameters)
    

    例:

    public class People: User
    {
       public People (int EmpID) : base (EmpID)
       {
          // Add more statements here.
       }
    }
    
  • 9

    从基类继承类时,可以通过实例化派生类来调用基类构造函数

    class sample
    {
        public int x;
    
        public sample(int value)
        {
            x = value;
        }
    }
    
    class der : sample
    {
        public int a;
        public int b;
    
        public der(int value1,int value2) : base(50)
        {
            a = value1;
            b = value2;
        }
    }
    
    class run 
    {
        public static void Main(string[] args)
        {
            der obj = new der(10,20);
    
            System.Console.WriteLine(obj.x);
            System.Console.WriteLine(obj.a);
            System.Console.WriteLine(obj.b);
        }
    }
    

    sample program的输出是

    50 10 20


    您还可以使用 this 关键字从另一个构造函数调用构造函数

    class sample
    {
        public int x;
    
        public sample(int value) 
        {
            x = value;
        }
    
        public sample(sample obj) : this(obj.x) 
        {
        }
    }
    
    class run
    {
        public static void Main(string[] args) 
        {
            sample s = new sample(20);
            sample ss = new sample(s);
    
            System.Console.WriteLine(ss.x);
        }
    }
    

    这个sample program的输出是

    20

  • 1

    像这样:

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

    下面是一个调用另一个构造函数的示例,然后检查它已设置的属性 .

    public SomeClass(int i)
        {
            I = i;
        }
    
        public SomeClass(SomeOtherClass soc)
            : this(soc.J)
        {
            if (I==0)
            {
                I = DoSomethingHere();
            }
        }
    
  • 50

    我正在改进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);
        }
    }
    
  • 6

    是的,你可以在通话基地之前调用其他方法或者这个!

    public class MyException : Exception
    {
        public MyException(int number) : base(ConvertToString(number)) 
        {
        }
    
        private static string ConvertToString(int number) 
        { 
          return number.toString()
        }
    
    }
    
  • 0

    Constructor chaining 即你可以使用"Base" for是一个关系,"This"可以用于同一个类,当你想在单个调用中调用多个Constructor时 .

    class BaseClass
    {
        public BaseClass():this(10)
        {
        }
        public BaseClass(int val)
        {
        }
    }
        class Program
        {
            static void Main(string[] args)
            {
                new BaseClass();
                ReadLine();
            }
        }
    

相关问题