C reflection of Reflection on the class property get or set values

  • 2020-05-30 19:51:06
  • OfStack

Recently, a friend called Insus learned about reflection 1 (Reflection), which provides encapsulation assemblies, modules, and types of objects (Type types). You can use reflection to dynamically create instances of a type, bind the type to an existing object, or get the type from an existing object and call its methods or access its fields and properties. If properties are used in your code, they can be accessed using reflection.
The following example is the Insus exercise set and get values for a category of properties.

First write a class, and then write a read-write property:
 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
/// <summary> 
/// Summary description for Member 
/// </summary> 
namespace Insus.NET 
{ 
public class Member 
{ 
private string _Name; 
public string Name 
{ 
get 
{ 
return _Name; 
} 
set 
{ 
_Name = value; 
} 
} 
public Member() 
{ 
// 
// TODO: Add constructor logic here 
// 
} 
} 
} 

Insus.NET1 is the asp.net program, and the exercise is also done at the site.
Create 1 web page with two namespace references:
 
using Insus.NET; 
using System.Reflection; 

Read and write properties:
 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using Insus.NET; 
using System.Reflection; 
public partial class _Default : System.Web.UI.Page 
{ 
protected void Page_Load(object sender, EventArgs e) 
{ 
// Instantiate the class  
Member objMember = new Member(); 
// To attribute set value  
PropertyInfo pi = objMember.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance); 
if (null != pi && pi.CanWrite) 
{ 
pi.SetValue(objMember, "Insus.NET", null); 
} 
// To attribute get value  
PropertyInfo pii = objMember.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance); 
if (null != pii && pi.CanRead) 
{ 
object obj_Name = pii.GetValue(objMember, null); 
Response.Write(obj_Name.ToString()); 
} 
} 
} 

Related articles: