c# - 使用 Expando 对象时如何将类型设置为可为空

标签 c# .net dynamic nullable expandoobject

我有一个 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/

相关文章:

使用 WPF C# 打印

c# - 将命令模式调整为建立多个 API 连接的单例

c# - 静态数据表内存何时被处置

.net - 字符串中的日期时间格式?

.net - 发出方法来覆盖非虚拟对象

c# - 我如何在 C# 中获得两列 winform 列表框?

c# - 如何使用 viewmodelocator 在 View 模型之间发送参数

c# - MVC通用类定位

c - 从c中的文件中读取分号后的整数 "unfixed"个数

c# - 使用从数组读取的属性创建 ExpandoObjects 列表