在 C# 中迭代​​泛型列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/284220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 21:36:09  来源:igfitidea点击:

Iterate though Generic List in C#

c#generics

提问by

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.

其中 V 的类型为 Item,即我的对象。

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.

当我调试并查看“元素”对象时,我可以看到“Quickwatch”中的所有属性,但我无法执行 element.IetmGuid。

回答by TcKs

foreach( object element in myList ) {
    Item itm = element as Item;
    if ( null == itm ) { continue; }
    Guid test = itm.ItemGuid;
}

回答by user34292

Your list should be declared like this:

你的列表应该这样声明:

List<V> myList = someMethod;

Where V is the type item.

其中 V 是类型项。

and then your iteration was correct:

然后你的迭代是正确的:

foreach(V element in myList)
{
    Guid test = element.IetmGuid;
}

回答by Daniel M

Try declaring your list like this:

尝试像这样声明你的列表:

List<Item> myList = someMethod;

回答by akmad

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

您是否对泛型 V 施加了限制?您需要告诉运行时 V 可以是您的Item类型的子类型的任何类型。

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

请注意,只有当您需要支持多种 Item(由 Item 的子类型表示)时,以这种方式使用泛型类才有意义。