我有以下几点:
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。
有趣的是谷歌搜索没什么好处.
发布于 2014-02-07 03:01:57
您正在寻找一个属性,但您拥有的是一个字段。属性具有get/get访问器,可以包含自定义代码(但通常不包含),而字段不包含。您可以将类更改为:
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 }发布于 2014-02-07 02:56:49
您的代码具有公共属性。是这种情况吗?您忽略了示例代码中最重要的部分。没有它,我们就不能重复你的问题。
无论如何,在这里,反射是错误的方法。您应该使用以下语法:
Timetable.Find(delegate(ICommonPropeeties a) { return a.ID == 12; });其中ICommonPropeties是由所有项实现的接口。
https://stackoverflow.com/questions/21618394
复制相似问题