C # Reflection (PropertyInfo Class)

Source: Internet
Author: User
Tags mscorlib

1. Introduction of namespaces: System.Reflection; Assembly: mscorlib (in mscorlib.dll)

2. Sample code (mainly GetType (), SetValue (), GetValue () method):

1UsingSystem;2UsingSystem.Collections.Generic;3UsingSystem.Linq;4UsingSystem.Reflection;5UsingSystem.Text;6UsingSystem.Threading.Tasks;78NamespaceReflection9{10ClassProgram11{12///<summary>13///Reflection describes assemblies, modules, types of objects (type types). You can use reflection to dynamically create an instance of a type, bind an instance to an existing object, or get a type from an existing object and call its methods or access its fields and properties14///If you use attributes in your code, you can use reflection to access them15///</summary>16Staticvoid Main (String[] args)17{1819//1. Explanations and examples of GetType ()20//21st//Summary:22//Gets the System.Type of the current instance.23//24//return Result:25//An System.Type instance that represents the exact run-time type of the current instance.2627//The following example obtains a simple reflection of its type using the static method gettype (all types derived from the object base class inherit the method)Student STU1 =New Student () {id =1, name ="Tom", length =175, DateTime = DateTime.Now};//Student STU2 =New Student () {id =2, name ="John doe", length =, DateTime = DateTime.Now};//name = "John Doe", DateTime = DateTime.Now3031var list =New list<student>();32List. ADD (STU1);33List. ADD (STU2);34Type Stutype =Stu1. GetType ();Type ListType =List. GetType ();37Console.WriteLine ("---------------getType () output Type----------------");Console.WriteLine (Stutype);//Type of output studentConsole.WriteLine (Stu1.id.GetType ());//Type of ID for output studentConsole.WriteLine (Stu1.name.GetType ());//Type of the name of the output studentConsole.WriteLine (Stu1.datetime.GetType ());//Type of datetime for output student43Console.WriteLine (ListType);//Type of output list454647//2. Explanations and examples of GetProperties ()48//49//Summary:50//Returns all the public properties of the current System.Type.51//52//return Result:53//An array of System.Reflection.PropertyInfo objects that represent all the public properties of the current System.Type. -or-if the current System.Type54//An empty array of type SYSTEM.REFLECTION.PROPERTYINFO without a public property.55propertyinfo[] Stupropertys =Stutype.getproperties ();propertyinfo[] Listpropertys =Listtype.getproperties ();5859//Console.WriteLine (Stupropertys.count ());60//Console.WriteLine (Stupropertys.length);6162//3. Explanations and examples of SetValue ()63//64//Summary:65//Sets the value of the property with an optional index value for the indexed property.66//67//Parameters:68//Obj:69//The object whose property values will be set.70//71//Value72//The new value for this property.73//74//Index 75//The optional index value of the indexed property. For a non-indexed property, this value should be null. 76//77//Exception: system.argumentexception:79/////The index array does not contain parameters of the required type. -or-the property's set accessor was not found. +//Bayi//system.reflection.targetexception:82//The object does not match the target type, or an attribute is an instance property but obj is null. SYSTEM.REFLECTION.TARGETPARAMETERCOUNTEXCEPTION:85//+///////-The number of parameters in index does not match the number of parameters used by indexed properties. +/////system.methodaccessexception:88//try to access private or protected methods in a class illegally. system.reflection.targetinvocationexception:91////////////////////// For example, the index value specified for an indexed property is out of range. The System.Exception.InnerException property indicates the cause of the error. The Console.WriteLine ("---------------SetValue () assigns a value to a property----------------"); PropertyInfo Stupro = stupropertys.firstordefault (x = X.name = = "Name");//Here is the property name for name 94 Stupro.setvalue (STU1, "King Five ", null); Console.WriteLine (Stu1.name); 96 97 98//4, GetType () method explanation and Example 99//100//Abstract: 101//Returns the property value of the specified object with an optional index value for the indexed property. 102//103//Parameter: 104//OBJ:105//The object whose property value will be returned. 106 the optional index value of the//107//index:108//indexed property. For a non-indexed property, the value should be null. 109//110//Return Result: 111//Specify the property value of the object. 112//113//exception: 114//system.argumentexception:115//The index array does not contain the parameters of the desired type. -or-the get accessor for the property was not found. //117//system.reflection.targetexception:118//The object does not match the target type, or an attribute is an instance property but obj is null. 119//120//system.reflection.targetparametercountexception:121//Index The number of parameters in the index does not match the number of parameters used by the indexed property. 122//123//system.methodaccessexception:124//attempt to illegally access a private or protected method in a class. //126//system.reflection.targetinvocationexception:127//Error retrieving property value. For example, the index value specified for an indexed property is out of range. The System.Exception.InnerException property indicates the cause of the error. Console.WriteLine ("---------------getValue () Traverse property Value----------------"), 129 foreach (Var v in stupropertys)//Traverse Property 130 {131 Console.WriteLine (V.getvalue (STU1, null));}133 134 135 console.readline (); 136}137}138 139 public class Student1 {141 public int id {get; set;} 142 public string Name {get; set;} 143 public decimal Length {get; set;} 144 public datetime datetime {get; set;} 145}146}

3. Operation Result:

4. The following are the main public members of the PropertyInfo type, for reference (excerpt from: Http://msdn.microsoft.com/zh-cn/library/system.reflection.propertyinfo (v= vs.110). aspx)

C # Reflection (PropertyInfo Class)

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.