繁体   English   中英

system.reflection无法获取属性值

[英]system.reflection unable to get property value

我有以下几点:

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。

有趣的是,谷歌搜索并没有带来太多收益...

您在寻找物业,但您拥有的是田野 属性具有的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 }

您的代码具有公共属性。 是这样吗 您已经省略了示例代码中最重要的部分。 没有它,我们将无法重现您的问题。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM