Accessing a Private Constructor from Outside the Class in C#

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

    In additional to @jgauffin's answer which tells how to call private constructors via reflection:

    Is it possible to change the modifiers of the private constructor?

    It seems that you are implementing Factory Pattern in your code. Thus the modifier is supposed to be internal.

    public class Product
    {
       //others can't create instances directly outside the assembly
       internal Product() { }    
    }
    public class ProductProvider
    {
       //they can only get standardized products by the provider
       //while you have full control to Product class inside ProductProvider
       public static Product CreateProduct()
       {
           Product p = new Product();    
           //standardize the product
           return p;
       }  
    }
    

    Extension methods

    public static MyExt
    {
       public static void DoSomething(this Product p) { }
    }
    

    Calling p.DoSomething() actually equals to MyExt.DoSomething(p). It's not putting this method into class Product.

提交回复
热议问题