我有一个 dynamic
类型的集合。我已将 double 值存储在集合中。对于某些记录,我没有将数据存储到其中。现在我需要将此类型作为 nullable
double 来执行一些操作。在使用 Expando
对象时,有什么方法可以将数据属性类型设置为 nullable
吗?
ObservableCollection<dynamic> dynamicItems = new ObservableCollection<dynamic>();
for (int j = 1; j <= 4; j++)
{
dynamic data = new ExpandoObject();
if (j == 2)
{
// not store the value when j is 2.
}
else
{
data.colValues = 12.2 * j;
}
dynamicItems.Add(data);
}
最佳答案
您可以尝试转换到Double?
,然后检查是否colValues == null
:
...
if (j == 2)
{
// not store the value when j is 2.
data.colValues = new Nullable<Double>(); // or (Double?) null;
}
else
{
data.colValues = (Double?) (12.2 * j);
}
...
// if colValues exists
if (null != data.colValues) {
Double v = data.colValues;
...
}
另一种方法是什么都不做,然后检查字段(即colValues
)是否存在,但是恕我直言,这不是< em>良好的实现:
if (j == 2)
{
// not store the value when j is 2. - literally do nothing
}
else
{
data.colValues = 12.2 * j;
}
...
// if colValues exists
if ((data as IDictionary<String, Object>).ContainsKey("colValues")) {
Double v = data.colValues; // or var v = data.colValues;
...
}
关于c# - 使用 Expando 对象时如何将类型设置为可为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32271872/