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

时间:2010-11-27 09:59:07

标签: c# reflection

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

谢谢

3 个答案:

答案 0 :(得分:20)

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 :(得分:1)

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

答案 2 :(得分:1)

object myObject;

PropertyInfo[] properties = myObject.GetType().GetProperties(BindingFlags.Instance);

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