Original: Use reflection in C # to get a struct-body instance
It is relatively simple to get an instance of a class object using reflection, as long as the class has an parameterless constructor or does not display a constructor that declares a parameter , you can use the following code
Static void Main (string[] args) { typeof(MyObject); object obj = type. GetConstructor (type.emptytypes). Invoke (null); Console.WriteLine (obj);} class myobject{}
I never found out that the original structure could not be instantiated like this.
In other ways, it seems that the struct uses reflection to not get its constructor ConstructorInfo object
There is an implicit constructor in the class, and the struct does not have a constructor function
I even tried to find a non-public constructor
Still no
This problem once bothered me for a long time .... The solution of the method is not difficult, so also did not take the matter, but today a friend asked the question, so summarize the issue, to the same encounter the problem of friends
It's very simple, just so you can.
Static void Main (string[] args) { typeof(mystruct); object obj1 = type. Assembly.createinstance (type. FullName);} struct mystruct{}
This method illustrates
Assembly.createinstance
Use a case-sensitive search to find the specified type from this assembly, and then use the system activator to create an instance of it.
using this method is not a class or a struct can be used, if the class as long as the guarantee that there is no parameter constructor can be
This method is not an advanced thing, mainly to the same students who have encountered this problem to explain
======================================================
Thank Karascanvas classmate, originally C # and activator such a class
Activator. CreateInstance (Type)
That's it.
Using reflection to get struct-body instances in C #