C#foreach interator如何生成空引用

C#foreach interator如何生成空引用,c#,C#,考虑C#中的这些语句: foreach(channel.Data中的var样本) { 如果(sample.TimeStampx不是null比x!=空。从技术上讲,可能会出现=运算符重载并返回true。另一个

考虑C#中的这些语句:

foreach(channel.Data中的var样本)
{                                                                                                                                                   
如果(sample.TimeStamp
此代码在VS2019 IDE中执行时返回一个NullReferenceException和review,表明变量“sample”的值为null。同时,“channel.Data”不是空的,并且有数千个数据点

所以,问题是,“sample”怎么可能被设置为null值

C#foreach interator如何生成空引用

轻松的

channel.Data=newsample[]{null,null,null};
foreach(channel.Data中的var样本){
if(sample.TimeStamp
如果你想避免这种情况,只需过滤它

foreach ( var sample in channel.Data.Where( x => x != null) )
{   
    if (sample.TimeStamp < placeholderMinLimit) 
        continue;
}
foreach(channel.Data.Where(x=>x!=null)中的var样本)
{   
if(sample.TimeStamp
yield null
在迭代器中工作。可枚举项不必只返回非null项。
通道。数据
从证据上讲是某种类型的集合,但这并不意味着该集合中包含的对象不为null。任何示例实例本身是否可以为
null
?(不是数组,而是数组中的一个条目)旁注(纯学术):
x=>x是object
x=>x不是null
x!=空
。从技术上讲,可能会出现
=x
null
时,code>运算符重载并返回
true
。另一个(冗长的)选项是
!ReferenceEquals(null,x)
channel.Data = new Sample[] { null, null, null };
foreach (var sample in channel.Data) {                                  
    if (sample.TimeStamp < placeholderMinLimit) 
        continue;
}
foreach ( var sample in channel.Data.Where( x => x != null) )
{   
    if (sample.TimeStamp < placeholderMinLimit) 
        continue;
}