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

问题描述 投票:0回答:3

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

谢谢

c# reflection
3个回答
26
投票
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
    }
}

1
投票
foreach(PropertyInfo pi in myobject.GetType().GetProperties(BindingFlags.Public))
{
    if (pi.GetValue(myobject)==null)
    {
        // do something
    }
}

1
投票
对象 myObject;

PropertyInfo[] 属性 = myObject.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance);

请参阅 http://msdn.microsoft.com/en-us/library/aa332493(VS.71).aspx

© www.soinside.com 2019 - 2024. All rights reserved.