一个例子using System;
using System.Reflection;class DynoProp
{
string m_sProp1;
string m_sProp2; public DynoProp()
{
} public DynoProp(string s1, string s2)
{
m_sProp1 = s1;
m_sProp2 = s2;
} public string Prop1
{
get {return m_sProp1;}
set {m_sProp1 = value;}
} public string Prop2
{
get {return m_sProp2;}
set {m_sProp2 = value;}
}
}class DynoTest
{
public static void Main()
{
DynoProp dp = new DynoProp();
dp.Prop1 = "Hello";
dp.Prop2 = "World";
Console.WriteLine("Before setting values with Reflection:");
Console.WriteLine("1st Property:\t{0}", dp.Prop1);
Console.WriteLine("2nd Property:\t{0}\n", dp.Prop2); PropertyInfo[] pis = dp.GetType().GetProperties();
for (int i=0; i < pis.Length; i++)
{
Object[] oParamList = null;
object oColl = pis[i].GetValue(dp,oParamList);
Console.WriteLine("Old Value: {0} Property:\t{1}", i, oColl);
pis[i].SetValue(dp,"new value " + i +" for property " + i, oParamList);
oColl = pis[i].GetValue(dp,oParamList);
Console.WriteLine("New Value: {0} Property:\t{1}\n", i, oColl);
} Console.WriteLine("After setting values with Reflection:");
Console.WriteLine("1st Property:\t{0}", dp.Prop1);
Console.WriteLine("2nd Property:\t{0}", dp.Prop2); }
}
using System.Reflection;class DynoProp
{
string m_sProp1;
string m_sProp2; public DynoProp()
{
} public DynoProp(string s1, string s2)
{
m_sProp1 = s1;
m_sProp2 = s2;
} public string Prop1
{
get {return m_sProp1;}
set {m_sProp1 = value;}
} public string Prop2
{
get {return m_sProp2;}
set {m_sProp2 = value;}
}
}class DynoTest
{
public static void Main()
{
DynoProp dp = new DynoProp();
dp.Prop1 = "Hello";
dp.Prop2 = "World";
Console.WriteLine("Before setting values with Reflection:");
Console.WriteLine("1st Property:\t{0}", dp.Prop1);
Console.WriteLine("2nd Property:\t{0}\n", dp.Prop2); PropertyInfo[] pis = dp.GetType().GetProperties();
for (int i=0; i < pis.Length; i++)
{
Object[] oParamList = null;
object oColl = pis[i].GetValue(dp,oParamList);
Console.WriteLine("Old Value: {0} Property:\t{1}", i, oColl);
pis[i].SetValue(dp,"new value " + i +" for property " + i, oParamList);
oColl = pis[i].GetValue(dp,oParamList);
Console.WriteLine("New Value: {0} Property:\t{1}\n", i, oColl);
} Console.WriteLine("After setting values with Reflection:");
Console.WriteLine("1st Property:\t{0}", dp.Prop1);
Console.WriteLine("2nd Property:\t{0}", dp.Prop2); }
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货