Accessing a Private Constructor from Outside the Class in C#

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

    if a class has only private and no public constructors, it can only be only accessible from nested classes within this class. what is worthy taking into consideration is the fact that classes with private default constructor cannot be derived. so it only makes sense to declare constructor or constructors as private (in a class which has no public instructors) when the instances from the class are aimed to be created only within nested classes inside this class. there is no other valid places for instancing this class.

    0 讨论(0)
  • 2020-12-30 22:27

    New answer (nine years later)

    There is now several overloads for Activator.CreateInstance that allow you to use non public constructors:

    Activator.CreateInstance(typeof(YourClass), true);
    

    true = use non public constructors.

    .

    Old answer

    Default constructors are private for a reason. The developer doesn't make it private for fun.

    But if you still want to use the default constructor you get it by using reflection.

    var constructor = typeof(Bob).GetConstructor(BindingFlags.NonPublic|BindingFlags.Instance, null, new Type[0], null);
    var instance = (Bob)constructor.Invoke(null);
    

    Edit

    I saw your comment about testing. Never test protected or private methods / properties. You have probably done something wrong if you can't manage to test those methods/properties through the public API. Either remove them or refactor the class.

    Edit 2

    Forgot a binding flag.

    0 讨论(0)
提交回复
热议问题