Accessing a Private Constructor from Outside the Class in C#

前端 未结 8 1662
梦如初夏
梦如初夏 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:13

    There are several ways around this issue:

    One: Make the constructor public. If you need to access it from outside the class why is it private (it might be that you only want to access the private constructor for testing, in which case this is a valid issue).

    Two: Make the constructor protected, then access it through a derived class:

    public class Bob
    {
        public String Surname { get; set; }
    
        protected Bob()
        { }
    
        public Bob(string surname)
        {
            Surname = surname;
        }
    }
    
    public class Fred : Bob
    {
        public Fred()
            : base()
        {
        }
    }
    

    Three: Use reflection (as shown by jgauffin).

提交回复
热议问题