【问题标题】:Using c#, How can I take benefit of using nullable valuetypes when I have a variable of object type?使用 c#,当我有对象类型的变量时,如何利用可空值类型?
【发布时间】:2011-01-12 23:17:24
【问题描述】:

使用 c#,当我有一个对象类型的变量时,如何利用可空值类型?

例如,我在一个类中有一个方法 Insert,它接受 4 个参数:

public int Update(Int32 serial, object deliveryDate, object quantity, object shiftTime)
{
    ....
    ....
    ....
}

您可以猜到,此方法在表中插入一条新记录。该表(Table1)有 4 个列:Serial int、DeliveryDate DateTime null、Quantity float not null 和 ShiftTime smallint null

现在,我的问题是:我如何才能利用可空值类型的优势,以及如何将对象转换为我想要的类型,如 DateTime?

谢谢

【问题讨论】:

    标签: c# object types


    【解决方案1】:

    你可以看看System.Nullable<T> 类型。它在 C# 中有一些快捷方式:

    public int Update(
        int serial, 
        DateTime? deliveryDate, 
        float? quantity, 
        short? shiftTime)
    

    这允许你调用这样的方法:

    Update(10, null, null, null);
    

    【讨论】:

      【解决方案2】:

      为什么你的参数首先是 object 类型的?为什么不是:

      public int Update(int serial, DateTime? deliveryDate,
                        double? quantity, short? shiftTime)
      

      (请注意,decimal 可能是比 double 更好的选择 - 值得考虑。)

      如果您可以更改您的方法签名,那可能就是要走的路。

      否则,您真正想问的是什么问题?如果您不能更改参数,但参数的类型应为 DateTime(或 null)、double(或 null)和 short(或 null),那么您可以将它们转换为可以为空的等价物。这会将 null 拆箱为该类型的 null 值,并将非 null 值拆箱为相应的非 null 值:

      object x = 10;
      int? y = (int?) x; // y = non-null value 10
      x = null;
      y = (int?) x; // y is null value of the Nullable<int> type
      

      编辑:回复评论...

      假设您有一个换班时间的文本框。有三个选项:它被填写但不恰当(例如“foo”),它是空的,或者它是有效的。你会做这样的事情:

      short? shiftTime = null;
      string userInput = shiftTimeInput.Text;
      if (userInput.Length > 0) // User has put *something* in
      {
          short value;
          if (short.TryParse(userInput, out value))
          {
              shiftTime = value;
          }
          else
          {
              // Do whatever you need to in order to handle invalid
              // input.
          }
      }
      // Now shiftTime is either null if the user left it blank, or the right value
      // Call the Update method passing in shiftTime.
      

      【讨论】:

      • 乔恩,在 GUI 中,我有一个 Web 表单,它从用户那里获取 4 个值。例如,表单有一个用于 ShiftTime 的文本框。但 ShiftTime 不是强制性的表单字段。所以用户可能没有为它输入任何值。在这种情况下,我应该将 Null 传递给 Table1 中的 ShiftTime 列。我该如何处理这个?
      猜你喜欢
      • 2019-12-17
      • 2011-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多