我如何允许此get为空?
public double? GetSignalAverage
{
get
{
var signalaverage = Gsmdata.Select(x => x.SignalStrength)
.Average();
return Math.Round(signalaverage, 2);
}
}
SignalStrength是一个Int
答案 0 :(得分:1)
您必须将SignalStrength
声明为int?
以允许null
值。 (如果不这样做,int
将是其默认值,即0.()即使这样,Average()
也会忽略这些值,如果有任何非null元素(请参阅{ {3}})。
如果它们都是null
,Average
将返回null
,您可以抓住并返回,如下所示:
double? signalaverage = Gsmdata.Select(x => x.SignalStrength)
.Average();
if(signalaverage == null)
{
return signalaverage; // which is essentially 'return null;'
}
else
{
return Math.Round(signalaverage, 2);
}
答案 1 :(得分:1)
检查集合是空还是空:
public double? GetSignalAverage
{
get
{
if(Gsmdata == null || GsmData.Count() == 0)
return null;
var signalaverage = Gsmdata.Select(x => x.SignalStrength)
.Average();
return Math.Round(signalaverage, 2);
}
}