//获取变量 using System; using System.Reflection; class MyClass ...{ privateint myProperty; // Declare MyProperty. publicint MyProperty ...{ get ...{ return myProperty; } set ...{ myProperty=value; } } } publicclass MyTypeClass ...{ publicstaticvoid Main(string[] args) ...{ try ...{ // Get the Type object corresponding to MyClass. Type myType=typeof(MyClass); // Get the PropertyInfo object by passing the property name. PropertyInfo myPropInfo = myType.GetProperty("MyProperty"); // Display the property name. Console.WriteLine("The {0} property exists in MyClass.", myPropInfo.Name); } catch(NullReferenceException e) ...{ Console.WriteLine("The property does not exist in MyClass."+ e.Message); } } }
//获取所有变量
class MyClass ...{ publicint myInt =0; publicstring myString =null; public MyClass() ...{ } publicvoid Myfunction() ...{ } } class Type_GetMembers ...{ publicstaticvoid Main() ...{ try ...{ MyClass myObject =new MyClass(); MemberInfo[] myMemberInfo; // Get the type of 'MyClass'. Type myType = myObject.GetType(); // Get the information related to all public member's of 'MyClass'. myMemberInfo = myType.GetMembers(); Console.WriteLine( " The members of class '{0}' are : ", myType); for (int i =0 ; i < myMemberInfo.Length ; i++) ...{ // Display name and type of the concerned member. Console.WriteLine( "'{0}' is a {1}", myMemberInfo[i].Name, myMemberInfo[i].MemberType); } } catch(SecurityException e) ...{ Console.WriteLine("Exception : "+ e.Message ); } } }
using System; using System.Reflection; // Define a class with a property. publicclass TestClass ...{ privatestring caption ="A Default caption"; publicstring Caption ...{ get...{ return caption; } set ...{ if (caption != value) ...{ caption = value; } } } } class TestPropertyInfo ...{ publicstaticvoid Main() ...{ TestClass t =new TestClass(); // Get the type and PropertyInfo. Type myType = t.GetType(); PropertyInfo pinfo = myType.GetProperty("Caption"); // Display the property value, using the GetValue method. Console.WriteLine(" GetValue: "+ pinfo.GetValue(t, null)); // Use the SetValue method to change the caption. pinfo.SetValue(t, "This caption has been changed.", null); // Display the caption again. Console.WriteLine("GetValue: "+ pinfo.GetValue(t, null)); Console.WriteLine(" Press the Enter key to continue."); Console.ReadLine(); } } /**//* This example produces the following output: GetValue: A Default caption GetValue: This caption has been changed Press the Enter key to continue. */