比如有如下的类:
public class MyClass
{
public float 属性1 { get; set; }
public float 属性2 { get; set; }
public float 属性3 { get; set; }
.... public float 属性100{ get; set; }
}
在主函数中遍历该类的所有属性(这个可以用反射实现),如果某个属性满足条件,则将该属性的值赋值,请问这个如何实现呢?
实现类似这样的伪代码
MyClass myClass=new MyClass();
public void 判断<T>(T 类名,string 属性名)
{
//在此已经获得该实例的类型
//在此已经确定要给该类的 属性i 赋值
期望为 myClass.属性i 赋值
}
给一个示例:
class Program
{
static void Main(string[] args)
{
SetSomeValue();
Console.ReadKey();
}
static void SetSomeValue()
{
List<Area> al = GetOrigialList(10).FindAll(
delegate(Area a) { return a.Area_ID > 5; }
);
foreach (Area a in al)
{
a.Area_Name = a.Area_Name + "[修改后的值]";
}
foreach (Area a in al)
{
Console.WriteLine(a.Area_ID.ToString() + "-" + a.Area_Name);
}
}
static List<Area> GetOrigialList(int num)
{
List<Area> al = new List<Area>();
for (int i = 0; i < num; i++)
{
Area a = new Area();
a.Area_ID = i;
a.Area_Name = "" + a.Area_ID + "名";
al.Add(a);
}
return al;
}
}
#region Area
public class Area
{
private int m_Area_ID;
public int Area_ID
{
get { return m_Area_ID; }
set { m_Area_ID = value; }
}
private string m_Area_Name;
public string Area_Name
{
get { return m_Area_Name; }
set { m_Area_Name = value; }
}
}
#endregion
@YTYT2002YTYT: 学习了
class Program
{
static void Main(string[] args)
{
SetSomeValue();
Console.ReadKey();
}
static void SetSomeValue()
{
List<Area> al = GetOrigialList(10).FindAll(
delegate(Area a) { return a.Area_ID > 5; }
);
foreach (Area a in al)
{
a.Area_Name = a.Area_Name + "[修改后的值]";
}
foreach (Area a in al)
{
Console.WriteLine(a.Area_ID.ToString() + "-" + a.Area_Name);
}
}
static List<Area> GetOrigialList(int num)
{
List<Area> al = new List<Area>();
for (int i = 0; i < num; i++)
{
Area a = new Area();
a.Area_ID = i;
a.Area_Name = "" + a.Area_ID + "名";
al.Add(a);
}
return al;
}
}
#region Area
public class Area
{
private int m_Area_ID;
public int Area_ID
{
get { return m_Area_ID; }
set { m_Area_ID = value; }
}
private string m_Area_Name;
public string Area_Name
{
get { return m_Area_Name; }
set { m_Area_Name = value; }
}
}
#endregion
利用反射为指定的名称的属性赋值