簡體   English   中英

如何在C#中迭代對象的所有屬性?

[英]How to iterate on all properties of an object in C#?

我是C#的新手,我想編寫一個函數來迭代對象的屬性並將所有空字符串設置為“”。 我聽說有可能使用一種叫做“反射”的東西,但我不知道怎么做。

謝謝

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
    }
}
foreach(PropertyInfo pi in myobject.GetType().GetProperties(BindingFlags.Public))
{
    if (pi.GetValue(myobject)==null)
    {
        // do something
    }
}
object myObject;

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

請參閱http://msdn.microsoft.com/en-us/library/aa332493(VS.71).aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM