首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >c# -如何遍历类字段和设置属性

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

Stack Overflow用户
提问于 2009-04-06 13:29:43
回答 6查看 102.8K关注 0票数 52

我不确定这是否可能,但我想在不显式引用field对象的情况下遍历一个类并设置一个field成员属性:

代码语言:javascript
复制
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; }
}

在我标记为答案的答案中,您需要添加:

代码语言:javascript
复制
  public static bool IsNullOrEmpty(this string source)
  {
    return (source == null || source.Length > 0) ? true : false;
  }
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2009-04-06 14:03:52

代码语言:javascript
复制
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);
    }
}
票数 30
EN

Stack Overflow用户

发布于 2009-04-06 14:20:11

下面是一个完整的工作示例:

代码语言:javascript
复制
public class Person
{
    public string Name { get; set; }
}

class Program
{
    static void PropertySet(object p, string propName, object value)
    {
        Type t = p.GetType();
        PropertyInfo info = t.GetProperty(propName);
        if (info == null)
            return;
        if (!info.CanWrite)
            return;
        info.SetValue(p, value, null);
    }

    static void PropertySetLooping(object p, string propName, object value)
    {
        Type t = p.GetType();
        foreach (PropertyInfo info in t.GetProperties())
        {
            if (info.Name == propName && info.CanWrite)
            {
                info.SetValue(p, value, null);
            }
        }
    }

    static void Main(string[] args)
    {
        Person p = new Person();

        PropertySet(p, "Name", "Michael Ellis");
        Console.WriteLine(p.Name);
        PropertySetLooping(p, "Name", "Nigel Mellish");
        Console.WriteLine(p.Name);
    }
}

编辑:添加了一个循环变量,这样你就可以看到如何循环遍历属性信息对象。

票数 35
EN

Stack Overflow用户

发布于 2009-04-06 14:40:36

使用我创建的以下扩展方法,您可以设置或获取任何属性值,即使它们是嵌套的

GetPropertyValue(customObject,"Property.Nested.Child.Name");

或设置

SetPropertyValue(customObject,"Property.Nested.Child.Name",“我的自定义名称”);

代码语言:javascript
复制
        private class TargetProperty
    {
        public object Target { get; set; }
        public PropertyInfo Property { get; set; }

        public bool IsValid { get { return Target != null && Property != null; } }
    }

    private static TargetProperty GetTargetProperty(object source, string propertyName)
    {
        if (!propertyName.Contains("."))
            return new TargetProperty { Target = source, Property = source.GetType().GetProperty(propertyName) };

        string[] propertyPath = propertyName.Split('.');

        var targetProperty = new TargetProperty();

        targetProperty.Target = source;
        targetProperty.Property = source.GetType().GetProperty(propertyPath[0]);

        for (int propertyIndex = 1; propertyIndex < propertyPath.Length; propertyIndex++)
        {
            propertyName = propertyPath[propertyIndex];
            if (!string.IsNullOrEmpty(propertyName))
            {
                targetProperty.Target = targetProperty.Property.GetValue(targetProperty.Target, null);
                targetProperty.Property = targetProperty.Target.GetType().GetProperty(propertyName);
            }
        }

        return targetProperty;
    }


    public static bool HasProperty(this object source, string propertyName)
    {
        return GetTargetProperty(source, propertyName).Property != null;
    }

    public static object GetPropertyValue(this object source, string propertyName)
    {
        var targetProperty = GetTargetProperty(source, propertyName);
        if (targetProperty.IsValid)
        {
            return targetProperty.Property.GetValue(targetProperty.Target, null);
        }
        return null;
    }

    public static void SetPropertyValue(this object source, string propertyName, object value)
    {
        var targetProperty = GetTargetProperty(source, propertyName);
        if(targetProperty.IsValid)
        {
            targetProperty.Property.SetValue(targetProperty.Target, value, null);
        }
    }

这里有几个测试

代码语言:javascript
复制
    [TestFixture]
public class ObjectExtensionsTest
{

    private class MockClass
    {
        public MockClass()
        {
            Nested = new NestedMockClass();
        }

        public string Id { get; set; }
        public string Name { get; set; }

        public string GetOnly { get { return "MockClass"; } }
        public string SetOnly { set { } }

        public NestedMockClass Nested { get; set; }
    }

    private class NestedMockClass
    {
        public string NestedId { get; set; }
        public string NestedName { get; set; }

        public string NestedGetOnly { get { return "NestedMockClass"; } }
        public string NestedSetOnly { set { } }
    }

    [Test]
    public void TestShouldFindProperty()
    {
        MockClass mockObject = new MockClass();

        Assert.IsTrue(mockObject.HasProperty("Id"));
        Assert.IsTrue(mockObject.HasProperty("Name"));
        Assert.IsTrue(mockObject.HasProperty("GetOnly"));
        Assert.IsTrue(mockObject.HasProperty("SetOnly"));
        Assert.IsTrue(mockObject.HasProperty("Nested"));
        Assert.IsTrue(mockObject.HasProperty("Nested.NestedId"));
        Assert.IsTrue(mockObject.HasProperty("Nested.NestedName"));
        Assert.IsTrue(mockObject.HasProperty("Nested.NestedGetOnly"));
        Assert.IsTrue(mockObject.HasProperty("Nested.NestedSetOnly"));
    }

    [Test]
    public void TestShouldGetPropertyValue()
    {
        MockClass mockObject = new MockClass();

        mockObject.Id = "1";
        mockObject.Name = "Name";
        mockObject.Nested.NestedId = "NestedId";
        mockObject.Nested.NestedName = "NestedName";

        Assert.AreEqual(mockObject.Id, mockObject.GetPropertyValue("Id"));
        Assert.AreEqual(mockObject.Name, mockObject.GetPropertyValue("Name"));
        Assert.AreEqual(mockObject.GetOnly, mockObject.GetPropertyValue("GetOnly"));
        Assert.AreEqual(mockObject.Nested.NestedId, mockObject.GetPropertyValue("Nested.NestedId"));
        Assert.AreEqual(mockObject.Nested.NestedName, mockObject.GetPropertyValue("Nested.NestedName"));

    }

    [Test]
    public void TestShouldSetPropertyValue()
    {
        MockClass mockObject = new MockClass();

        mockObject.SetPropertyValue("Id", "1");
        mockObject.SetPropertyValue("Name", "Name");
        mockObject.SetPropertyValue("Nested.NestedId", "NestedId");
        mockObject.SetPropertyValue("Nested.NestedName", "NestedName");

        Assert.AreEqual(mockObject.Id, "1");
        Assert.AreEqual(mockObject.Name, "Name");
        Assert.AreEqual(mockObject.Nested.NestedId, "NestedId");
        Assert.AreEqual(mockObject.Nested.NestedName, "NestedName");

    }
}

希望你会发现它是有用的。

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/721441

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档