Share via

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#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


Answer accepted by question author

Jack J Jun 25,306 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.

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

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