簡體   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