質問

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

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top