如何在ObservableCollection中访问对象的属性?

时间:2017-06-28 09:07:28

标签: c# wpf silverlight

我有一个通用的ObservableCollection

public ObservableCollection<T> _DGModels;

我将数据插入到ObservableCollection

public static ObservableCollection<dynamic> GetDGModelFromDatabase()
    {

        return new ObservableCollection<dynamic>
        {
            new Student { FirstName="Tom", LastName="Jones"},
            new Student { FirstName="Dick", LastName="Tracey"},
            new Student { FirstName="Harry", LastName="Hill"},
            new Student { FirstName="Jack" , LastName="Sparrow"},
            new Student { FirstName="Davy" , LastName="Jones"}
        };
    }

每个插入的数据都是类

的实例
public class Number : INotifyPropertyChanged
{
    public int firstNumber;
    public int lastNumber;

    public int FirstNumber

    public int LastNumber

    public int PlusNumber


    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propertyName)

}

我的问题是如何使用Type.GetProperty()访问Number的属性,即FirstName或LastName?

1 个答案:

答案 0 :(得分:0)

要使用反射获取属性FirstName(或LastName)的值,您只需按照要求使用GetProperty(),如下所示:

Number num = new Number() { FirstNumber = 1, LastNumber = 5 };

int first = (int)num.GetType().GetProperty("FirstNumber").GetValue(num,null);

Console.WriteLine(first);

假设您Number类看起来像这样:

public class Number : INotifyPropertyChanged
{
    public int FirstNumber { get; set; }
    public int LastNumber { get; set; }
    public int PlusNumber { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propertyName)
    { 
        //... 
    }
}