Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 遍历IEnumerable列表<;MyAbstractClass>;重置每个项目的属性_C#_Foreach_Abstract Class_Ienumerable - Fatal编程技术网

C# 遍历IEnumerable列表<;MyAbstractClass>;重置每个项目的属性

C# 遍历IEnumerable列表<;MyAbstractClass>;重置每个项目的属性,c#,foreach,abstract-class,ienumerable,C#,Foreach,Abstract Class,Ienumerable,是否有任何原因表明遍历IEnumerable会重置每个项的属性 假设我有一个列表作为项目: public abstract class MyAbstractClass{ public virtual string ID {get; set;} } public class MyClass : MyAbstractClass { public string ID {get; set;} } public static string MyMethod (IEnume

是否有任何原因表明遍历
IEnumerable
会重置每个项的属性

假设我有一个列表作为项目:

 public abstract class MyAbstractClass{
  public virtual string ID {get; set;}
 }

public class MyClass : MyAbstractClass {
      public string ID {get; set;}
     }

public static string MyMethod (IEnumerable<MyAbstractClass> items)
{
  //At this moment I can see that items are populated correctly.
  foreach (MyAbstractClass item in items)
  {
    //at this moment each item is kind of reset and all it's properties are null
  }
}
公共抽象类MyAbstractClass{
公共虚拟字符串ID{get;set;}
}
公共类MyClass:MyAbstractClass{
公共字符串ID{get;set;}
}
公共静态字符串MyMethod(IEnumerable项)
{
//此时,我可以看到项目已正确填充。
foreach(项目中的MyAbstractClass项目)
{
//此时,每个项都是一种重置,其所有属性都为空
}
}
为什么会发生这种事?我不确定我是不是做错了什么

提前谢谢

编辑:


MyClass的I可枚举列表被传递给MyMethod。

您可能想使用接口而不是抽象类?我想这可能取决于您的
IEnumerable
是什么。理论上,实现它的类可能是邪恶的,并在迭代时改变其项,尽管我高度怀疑在本例中是否是这样。我认为您需要详细说明:在不进行迭代的情况下,如何在迭代之前“看到项目被正确填充”?项目是如何“重置”的?你能展示一个前后状态的样本吗?编辑:还有,
项目的类型是什么?它是一个
列表
,还是一些延迟的LINQ到对象查询,还是一个数据库访问查询?我可以看到,在断点的帮助下,项目被正确填充。我可以看到项目中有真正的值。我甚至在调用items的ToArray()方法时尝试了立即窗口,然后返回的数组的ID值为空。@Ashkan:我认为您必须发布代码,说明如何生成
items
参数,最好是一个简短的程序,我们可以复制/粘贴并复制自己。@Ashkan:是的,如果父类的属性没有被派生类显式重写,那么这两个属性被认为是完全不同的,并且没有任何关联。当编译时类型为一种或另一种时,访问属性将访问它们自己的特定属性值。只有重写它,它们才本质上是相同的共享属性。