Reputation:
public class Item
{
private int _rowID;
private Guid _itemGUID;
public Item() { }
public int Rid
{
get
{
return _rowID;
}
set { }
}
public Guid IetmGuid
{
get
{
return _itemGuid;
}
set
{
_itemGuid= value;
}
}
}
The above is my custom object.
I have a list:
List<V> myList = someMethod;
where V is of type Item, my object.
I want to iterate and get the properties as such
foreach(V element in mylist)
{
Guid test = element.IetmGuid;
}
When I debug and look at the 'element' object I can see all the properties in the 'Quickwatch' but I cannot do element.IetmGuid.
Upvotes: 4
Views: 44496
Reputation: 19791
Are you putting a constraint on the generic type V? You'll need to tell the runtime that V can be any type that is a subtype of your Item
type.
public class MyGenericClass<V>
where V : Item //This is a constraint that requires type V to be an Item (or subtype)
{
public void DoSomething()
{
List<V> myList = someMethod();
foreach (V element in myList)
{
//This will now work because you've constrained the generic type V
Guid test = element.IetmGuid;
}
}
}
Note, it only makes sense to use a generic class in this manner if you need to support multiple kinds of Items (represented by subtypes of Item).
Upvotes: 5
Reputation: 1597
Try declaring your list like this:
List<Item> myList = someMethod;
Upvotes: 3
Reputation: 41
Your list should be declared like this:
List<V> myList = someMethod;
Where V is the type item.
and then your iteration was correct:
foreach(V element in myList)
{
Guid test = element.IetmGuid;
}
Upvotes: 1
Reputation: 26642
foreach( object element in myList ) {
Item itm = element as Item;
if ( null == itm ) { continue; }
Guid test = itm.ItemGuid;
}
Upvotes: 1