简体   繁体   English

system.reflection无法获取属性值

[英]system.reflection unable to get property value

I have the following: 我有以下几点:

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 }

At the start of the code, I have a list of item which I added using 在代码的开头,我有一个列表,使用

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

Here I want to get Agenda with Item that has ID=12. 在这里,我想获取具有ID = 12的商品的议程。 I tried using 我尝试使用

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 ....
}

Why does it return the error message "Sequence contains no matching element"? 为什么返回错误消息“序列不包含匹配元素”?

I also tried 我也试过

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

but it returns "Object reference not set to an instance of an object". 但它返回“对象引用未设置为对象的实例”。 It cannot find the ID. 它找不到ID。

It's funny that don't get much from googling ... 有趣的是,谷歌搜索并没有带来太多收益...

You are looking for a property but what you have is a field . 您在寻找物业,但您拥有的是田野 A property has get/get accessors than can contain custom code (but usually don't) whereas a field does not. 属性具有的get / get访问器可能包含自定义代码(但通常不包含),而字段则没有。 You can change your class to: 您可以将课程更改为:

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;}
}

However, you state 但是,您声明

item can be of any object type but has common properties 项目可以是任何对象类型,但具有共同的属性

If that's the case, then you should define an interface that they all implement. 如果是这种情况,那么您应该定义一个它们都实现的接口 That way, you don't need reflection: 这样,您就不需要反思:

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 }

Your code assumes public properties. 您的代码具有公共属性。 Is this the case? 是这样吗 You have omitted the most important part of the sample code. 您已经省略了示例代码中最重要的部分。 Without it, we cannot reproduce your issue. 没有它,我们将无法重现您的问题。

Regardless, reflection is the wrong approach here. 无论如何,反思是错误的方法。 You should use the following syntax: 您应该使用以下语法:

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

Where ICommonPropeties is an interface implemented by all items. ICommonPropeties是由所有项目实现的接口。

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

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