相关疑难解决方法(0)

c# - 如何遍历类字段并设置属性

我不确定这是否可行但我想迭代一个类并设置一个字段成员属性而不显式引用字段对象:

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 { …
Run Code Online (Sandbox Code Playgroud)

c# field properties class set

50
推荐指数
5
解决办法
9万
查看次数

访问结构的字段

为什么以下代码不产生输出?

static void Main(string[] args)
{
    FieldInfo[] fi = typeof(MyStruct).GetFields(BindingFlags.Public);
    foreach (FieldInfo info in fi)
    {
        Console.WriteLine(info.Name);
    }
}

public struct MyStruct
{
    public int one;
    public int two;
    public int three;
    public int four;
    public int five;
    public int six;
    public bool seven;
    public String eight;
}
Run Code Online (Sandbox Code Playgroud)

c# reflection

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

c# ×2

class ×1

field ×1

properties ×1

reflection ×1

set ×1