Create object instance without invoking constructor?

后端 未结 11 1986
不知归路
不知归路 2020-11-28 05:01

In C#, is there a way to instantiate an instance of a class without invoking its constructor?

Assume the class is public and is defined in a 3rd par

11条回答
  •  野性不改
    2020-11-28 05:17

    EDIT: You updated your question, you want to construct a class without a constructor. Or call a default "Empty Constructor".

    This cannot be done, as the compiler will not generate a default constructor if there is already one specified. However, for the benefit of the readers, here is how to get at a internal, protected, or private constructor:

    Assuming your class is called Foo:

    using System.Reflection;
    
    // If the constructor takes arguments, otherwise pass these as null
    Type[] pTypes = new Type[1];
    pTypes[0] = typeof(object);    
    object[] argList = new object[1];
    argList[0] = constructorArgs;
    
    ConstructorInfo c = typeof(Foo).GetConstructor
        (BindingFlags.NonPublic |
         BindingFlags.Instance,
         null,
         pTypes,
         null);
    
    Foo foo = 
        (Foo) c.Invoke(BindingFlags.NonPublic,
                       null, 
                       argList, 
                       Application.CurrentCulture);
    

    Ugly, but works.

    Of course, there may be a perfectly legitimate reason to mark a constructor as internal, so you should really consider the logistics of what you want before you abuse that class by getting at it with reflection.

提交回复
热议问题