2014-02-07 53 views
0

我有以下几点:的System.Reflection无法获得属性值

List<Agenda> Timetable; 

public class Agenda 
{ 
    public Object item; //item can be of any object type but has common properties 
} 

class MasterItem 
{ 
    public long ID; 
} 

class item1:MasterItem { //properties and methods here } 

class item2:MasterItem { //properties and methods here } 

在代码的开始,我有我添加使用

item1 sItem = new item1() { //Initialize properties with values } 
Timetable.Add(new Agenda {item = sItem); 

在这里我要项的列表获得ID为12的项目的议程。我试过使用

object x = Timetable.Find(delegate (Agenda a) 
{ 
    System.Reflection.PropertyInfo pinfo = a.item.GetType().GetProperties().Single(pi => pi.Name == "ID"); //returned Sequence contains no matching element 
    return .... 
} 

它为什么会返回错误消息“序列包含没有匹配的元素”?

我也试过

a.item.GetType().GetProperty("ID") 

但它返回“未设置为一个对象的实例对象引用”。它找不到该ID。

有趣的是,不要从谷歌搜索得到很多...

回答

2

您正在寻找一个物业,但你有什么是字段。一个属性具有获取/获取访问者的权限,而可以包含包含自定义代码(但通常不包含),而字段不包含。您可以把班级改为:

public class Agenda 
{ 
    public Object item {get; set;} //item can be of any object type but has common properties 
} 

class MasterItem 
{ 
    public long ID {get; set;} 
} 

但是,你的状态

项目可以是任何对象类型,但具有共同的属性

如果是这样的话,那么你应该定义它们都实现的接口。这样,你不需要反思:

public class Agenda 
{ 
    public ItemWithID item {get; set;} 
} 


Interface ItemWithID 
{ 
    long ID {get; set;} 
} 

class MasterItem : ItemWithID 
{ 
    public long ID {get; set;} 
} 

class item1:MasterItem { //properties and methods here } 

class item2:MasterItem { //properties and methods here } 
+0

这有助于很多。谢谢! – cSharpDev

1

您的代码假定公共属性。是这样吗?您省略了示例代码中最重要的部分。没有它,我们不能重现您的问题。

无论如何,反射在这里是错误的方法。您应该使用以下语法:

Timetable.Find(delegate(ICommonPropeeties a) { return a.ID == 12; }); 

其中ICommonPropeties是由所有项目实现的接口。

+0

是的,我错过了!谢谢!它现在的魅力... – cSharpDev