How to create a private constructor with parameters from a DLL using reflection in C#?

Everett Lee 21 Reputation points
2022-06-22T03:02:32.357+00:00

It is easy to create a private constructor without parameters.

Blockquote object Activator.Createlnstance (Type type, bool nonPublic)
Blockquote Creates an instance of the specified type using that type's default constructor.
Blockquote type: The type of object to create.

But how to create a private constructor with parameters?

The following is my code(in the pictures).
213594-screenshot-1.png213576-screenshot-2.png

Developer technologies C#
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2022-06-22T06:22:06.433+00:00

    @Everett Lee , Welcome to Microsoft Q&A, you could try to use Type.GetConstructor Method to get the correspond Constructor and use invoke method to create the instance.

    Here is a code example you could refer to.

            Assembly assembly = Assembly.LoadFrom("ClassLibrary1.dll");  
            Type type = assembly.GetType("ClassLibrary1.Class1");  
            object [] paramValues = new object[] { "Test1",'1'};  
            Type[] paramTypes = new Type[] { typeof(string), typeof(char) };  
            object instance=type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic,null, paramTypes, null).Invoke(paramValues);  
    

    Result:

    213701-image.png

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.