Using reflection to get struct-body instances in C #

Source: Internet
Author: User

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 #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.