如何在 C# 中迭代​​对象的所有属性?

2024-04-28

我是 C# 新手,我想编写一个函数来迭代对象的属性并将所有空字符串设置为“”。我听说可以使用称为“反射”的东西,但我不知道如何操作。

Thanks


public class Foo
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
    public int Prop3 { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var foo = new Foo();

        // Use reflection to get all string properties 
        // that have getters and setters
        var properties = from p in typeof(Foo).GetProperties()
                         where p.PropertyType == typeof(string) &&
                               p.CanRead &&
                               p.CanWrite
                         select p;

        foreach (var property in properties)
        {
            var value = (string)property.GetValue(foo, null);
            if (value == null)
            {
                property.SetValue(foo, string.Empty, null);
            }
        }

        // at this stage foo should no longer have null string properties
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 C# 中迭代​​对象的所有属性? 的相关文章

随机推荐