Generic and reflection

Source: Internet
Author: User

Generics and reflection often work together, so let's take a look.

 

C # is a strongly typed language. Generally, the return type and parameter type of the function are good early in the morning, which makes it not as convenient to use as Js in many cases.

Therefore, with this generic type, your functions and parameters can be called to determine the type.

Public t ABC <t> (T word) {return word; return default (t); // The keyword default can return nullable for the reference type, and return 0 for the int type, the feeling of initializing a t} ABC <string> ("X "); // struct indicates the value type. // The advantage is that if the parameter is a value type, you do not need to use the famous test (100) instead of the test <int> (100 ); public void test <t> (T number) where T: struct {int z = convert. toint32 (number); // call test (100);} // The following does not know where the benefit is used, public void Test2 <t> (T lei) where T: class {} public void test3 <t> () where T: stooges {} public t test4 <t> () where T: New () {T abc = new T (); return ABC;} public class stooges {}

I don't know where to use it with where. I will study it later.

 

Reflection allows our code to dynamically obtain the attribute values of some objects or classes during runtime, and even call them.

First, let's get all the attributes and values of an object. JS is for (var attr in object) {object [ATTR] = value, ATTR = ATTR}

VaR OBJ = new ABC (); Type T = typeof (ABC); // typeof (class) instead of typeof (object) Oh Type V = obj. getType (); // obj. getType () is typeof (Object Class) propertyinfo [] attrs = obj. getType (). getproperties (bindingflags. instance | bindingflags. public); // get attrs foreach (propertyinfo ATTR in attrs) {string key = ATTR. name; // get ATTR name object value = ATTR. getvalue (OBJ, null); // get value
Type type = ATTR. propertytype; // type}

The key is the type. You can do a lot after obtaining the type.

Common Methods

T. getproperty ("key "). getvalue (OBJ, null); // read a key value T. getproperty ("key "). setvalue (OBJ, "", null); // write a value to key // note that if it is a dictionary T. getproperty ("item "). getvalue (OBJ, new [] {"ID"}); // get the item first and then use new [] {put the specified key here}

 

 

Let's take a look at the more detailed

    class MyClass    {        public int x { get; set; }        public int y { get; set; }        public MyClass(int i)        {            x = y + i;        }        public MyClass(int i, int j)        {            x = i;            y = j;        }        public int sum()        {            return x + y;        }    }

 

We want to obtain the constructor of this class.

Type T = typeof (myclass); constructorinfo [] constructors = T. getconstructors (); // use this method to obtain the constructor list for (INT I = 0; I <constructors. length; I ++) {constructorinfo constructor = constructors [I]; // The constructor is also a method, so getparameters parameterinfo [] parameters = constructor. getparameters (); // obtain the parameter list of the current constructor string paratypename = parameters [0]. parametertype. name; // parameter type name of the method string paraname = parameters [0]. name; // Parameter Name of the method} // call the constructor object [] ARGs = new object [2]; ARGs [0] = 10; ARGs [1] = 20; // directly instantiate object instance = constructors [0] without using new. invoke (ARGs); // instantiate a type object with two parameters for this constructor. If the parameter is null, It is null.
Object instance = (t) activator. createinstance (t); there is also a method for this instance, it is unclear whether the parameter does not exist

 

Call Method

Methodinfo [] Methods = T. getmethods (bindingflags. public | bindingflags. declaredonly | bindingflags. instance); foreach (methodinfo method in methods) {string return_name = method. returntype. name; // type of the returned method string name = method. name; If (name. equals ("sum", stringcomparison. ordinal) // specify the method name to call {int value = (INT) method. invoke (instance, null); // instance is a good object of the previous instance, and the method is in this object }}

 

Below are some references

Type T = typeof (myclass); console. writeline ("---------------- method ------------------"); methodinfo [] Methods = T. getmethods (); foreach (methodinfo method in methods) {console. writeline ("method:" + method); // console. writeline (method); // console. writeline ("Return Value:" + method. returnparameter);} console. writeline ("--------------- field -----------------"); // field, such as private static string name; fieldinfo [] fields = T. getfields (bindingflags. nonpublic | bindingflags. instance | bindingflags. static); foreach (fieldinfo field in fields) {console. writeline ("field:" + field);} console. writeline ("-------------- member --------------------"); // The member is the method and attribute memberinfo [] members = T. getmembers (); foreach (memberinfo member in members) {console. writeline ("member:" + member);} console. writeline ("-------------- property --------------------"); // attribute propertyinfo [] properties = T. getproperties (); foreach (propertyinfo property in properties) {console. writeline ("Property:" + property);} console. writeline ("-------------- constructor ------------------"); // constructorinfo [] constructors = T. getconstructors (bindingflags. nonpublic | bindingflags. instance); foreach (constructorinfo constructor in constructors) {console. writeline ("constructor:" + constructor );}

 

You do not need to remember the call clearly. You only need to know what can be obtained and called Using Reflection.

For a long time, we use the generic writing method. For example, our generic is an uncertain class, and then we need to obtain the ATTR value, you can use reflection.

You can also use string to call methods. This method is widely used in JS, for example, OBJ ["methodname"] (). reflection can also be used here.

P.s: the reflection performance is very slow. It can also be said that the dynamics are slow. This is normal. For Performance Optimization of reflection, refer to dynamic programming.

 

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.