Accessing a Private Constructor from Outside the Class in C#

前端 未结 8 1595
梦如初夏
梦如初夏 2020-12-30 21:52

If I define a class with a private default constructor and a public constructor that has parameters, how can I access the private constructor?

public class Bo         


        
8条回答
  •  囚心锁ツ
    2020-12-30 22:15

    public class demo
    {
       private demo()
        {
            Console.WriteLine("This is no parameter private constructor");
        }
        public demo(int a)
        {
            demo d = new demo('c');// u can call both private contstructors from here
            demo dd = new demo();
            Console.WriteLine("This is one parameter public constructor");
        }
        private demo(char a)
        {
            Console.WriteLine("This is one parameter public constructor::" + a);
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            demo obj = new demo(7);
            // demo obj = new demo();  // it will raise error
            Console.ReadLine();
        }
    }
    

提交回复
热议问题