C # basic series -- Reflection notes

Source: Internet
Author: User

C # basic series -- Reflection notes
Reflection has been used for several years, but I have always thought that the concept of anti-reflection is very abstract. I will summarize this knowledge point when I have time. 1. Why reflection is required: When reflection is initially used, it is always incomprehensible as a side dish. Since we can get an object through a new object, and then call attributes and methods through the object, so why do we need reflection to call it? Later, I found out that this is a problem of binding first or later. Many developers who are using reflection usually have such concerns: Since code can be written during development, it is not only tedious, but also inefficient. Bloggers think it is mainly about applicability. If your system does not have high scalability and flexibility requirements, you do not have to consider reflection. However, in architecture design, there are many things that need to be reused. In some specific scenarios, if you do not get a specific class, you must use reflection. The blogger summarized the reflection scenarios he has used: (1) Sometimes he does not know the specific type and can get class objects through dll; (2) some special methods, generic classes are passed in, and some special services need to be processed through reflection. (3) reflection is required for mutual conversion of the DataTable and List <T> methods; 2. How to Use reflection: (1) obtain the class member from the reflection dll: there is a Person class in an unknown dll.

Public class Person {private string address; private string email; public string Name {set; get;} public int Age {set; get;} public void SayHello () {Console. writeLine ("hello");} public static string MystaticPro {set; get;} public static void MyStatic () {Console. writeLine ("I Am a static method ");}}

 

Get the Person class through the reflected dll
Static void Main (string [] args) {// reflection dll var strDllPath = Path. combine (AppDomain. currentDomain. baseDirectory, "dll \ ReflectorDLL. dll "); var oAssembly = Assembly. loadFile (strDllPath); var lstTypes = oAssembly. getTypes (); foreach (var oType in lstTypes) {if (oType. name = "Person") {// by default, all public members under the class var lstMembers = oType are obtained. getMembers (); foreach (var oMem in lstMembers) {Console. the member name obtained by WriteLine ("GetMembers () method:" + oMem. name);} Console. writeLine (""); // by default, all public attributes under the class var lstProperty = oType. getProperties (); foreach (var oProp in lstProperty) {Console. the member name obtained by WriteLine ("GetProperties () method:" + oProp. name);} Console. writeLine (""); // by default, all public fields under the class var lstField = oType. getFields (); foreach (var oField in lstField) {Console. the member name obtained by WriteLine ("GetFields () method:" + oField. name) ;}} Console. readKey ();}

 

Expected result (2) Private member of the reflected object: Generally, private attributes are rarely used. We will use private fields as an example to describe the above example:
Static void Main (string [] args) {// reflection dll var strDllPath = Path. combine (AppDomain. currentDomain. baseDirectory, "dll \ ReflectorDLL. dll "); var oAssembly = Assembly. loadFile (strDllPath); var lstTypes = oAssembly. getTypes (); foreach (var oType in lstTypes) {if (oType. name = "Person") {// all public fields under the class var lstField = oType are obtained by default. getFields (BindingFlags. nonPublic | BindingFlags. instance); foreach (var oField in lstField) {Console. the member name obtained by WriteLine ("GetFields () method:" + oField. name) ;}} Console. readKey ();}

 

(3) static member of the reflection object:
Static void Main (string [] args) {// reflection dll var strDllPath = Path. combine (AppDomain. currentDomain. baseDirectory, "dll \ ReflectorDLL. dll "); var oAssembly = Assembly. loadFile (strDllPath); var lstTypes = oAssembly. getTypes (); foreach (var oType in lstTypes) {if (oType. name = "Person") {// by default, all public members under the class var lstMembers = oType are obtained. getMembers (BindingFlags. public | BindingFlags. static); foreach (var oMem in lstMembers) {Console. the member name obtained by WriteLine ("GetMembers () method:" + oMem. name);} Console. writeLine (""); // by default, all public fields under the class var lstField = oType. getFields (BindingFlags. nonPublic | BindingFlags. instance); foreach (var oField in lstField) {Console. the member name obtained by WriteLine ("GetFields () method:" + oField. name) ;}} Console. readKey ();}

 

There are enumeration types and so on. Basically, they are all processed on BindingFlags. (4) operations to get objects and objects through reflection: There are two main methods to get objects through reflection:
Public static T GetModel <T> (T oModel) {var model = default (T); // method 1 for getting an object: model = (T) typeof (T ). getConstructor (new System. type [] {}). invoke (new object [] {}); // returns the entity of the generic class through reflection. // method 2 for getting the object: model = (T) Activator. createInstance (typeof (T); // logic processing ...... return model ;}

 

Values and values of object attributes:
// Convert the List set to DataTable public static DataTable ListFillTable (object obj) {if (! (Obj is IList) {return null;} var objlist = obj as IList; if (objlist = null | objlist. count <= 0) {return null;} var tType = objlist [0]; DataTable dt = new DataTable (tType. getType (). name); DataColumn column; DataRow row; System. reflection. propertyInfo [] myPropertyInfo = tType. getType (). getProperties (BindingFlags. public | BindingFlags. instance); foreach (var t in objlist) {if (t = null) {continue;} row = dt. newRow (); for (int I = 0, j = myPropertyInfo. length; I <j; I ++) {System. reflection. propertyInfo pi = myPropertyInfo [I]; string name = pi. name; if (dt. columns [name] = null) {var coltype = pi. propertyType; if (coltype. name = "Nullable '1") {// coltype = typeof (System. DBNull); column = new DataColumn (name);} else {column = new DataColumn (name, coltype);} dt. columns. add (column);} row [name] = pi. getValue (t, null);} dt. rows. add (row) ;}return dt ;}

 

Related Article

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.