C#中 - 如何通过类字段和属性集迭代 [英] c# - How to iterate through classes fields and set properties
本文介绍了C#中 - 如何通过类字段和属性集迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道这是可能的,但我想通过一个类来遍历和设置字段的成员属性,而不参照Field对象明确:
公共类Employee
{
公众人物_person =新的Person(); 公共无效DynamicallySetPersonProperty()
{
的MemberInfo [] =成员this.GetType()GetMembers()。 的foreach(的MemberInfo构件在members.Where(一个= GT; a.Name ==_person))
//获取_person场
{ 类型type = member.GetType();
的PropertyInfo道具= type.GetProperty(名称); //好,这个工程,现在为它设置的值 //这行不工作 - 错误是未找到属性集法
prop.SetValue(部件,新的名称,NULL);
}
}
}
公共类Person
{
公共字符串名称{;组; }
}
在我标记为需要添加答案的答案:
公共静态布尔IsNullOrEmpty(此字符串源)
{
返回(来源== NULL || source.Length大于0)?真假;
}
感谢
谢谢,低于一些优秀的答案得到它为我工作。
解决方案
公共类Person
{
公共字符串名称{;组; }
}公共类员工
{
公众人物的人=新的Person(); 公共无效DynamicallySetPersonProperty()
{
VAR P =的GetType()getfield命令(人)的GetValue(本)。;
。p.GetType()的getProperty(姓名)的SetValue(P,新名字,NULL);
}
}
I am not sure if this is possible but I want to iterate through a class and set a field member property without referring to the field object explicitly:
public class Employee
{
public Person _person = new Person();
public void DynamicallySetPersonProperty()
{
MemberInfo[] members = this.GetType().GetMembers();
foreach (MemberInfo member in members.Where(a => a.Name == "_person"))
//get the _person field
{
Type type = member.GetType();
PropertyInfo prop = type.GetProperty("Name"); //good, this works, now to set a value for it
//this line does not work - the error is "property set method not found"
prop.SetValue(member, "new name", null);
}
}
}
public class Person
{
public string Name { get; set; }
}
In the answer that I marked as the answer you need to add:
public static bool IsNullOrEmpty(this string source)
{
return (source == null || source.Length > 0) ? true : false;
}
THANKS
Thanks, some excellent answers below that got it working for me.
解决方案
public class Person
{
public string Name { get; set; }
}
public class Employee
{
public Person person = new Person();
public void DynamicallySetPersonProperty()
{
var p = GetType().GetField("person").GetValue(this);
p.GetType().GetProperty("Name").SetValue(p, "new name", null);
}
}
这篇关于C#中 - 如何通过类字段和属性集迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文