【问题标题】:Question mark '?' given in arguments of a method [duplicate]问号“?”在方法的参数中给出[重复]
【发布时间】:2017-05-01 00:14:42
【问题描述】:

我有一个代码,其中包含一个具有以下方法的类:

public string AddEvent(DateTime date, int eventCount, int? eventId, string eventGuid){...}

我的问题是那里的问号有什么作用?我猜这与重载有关,因为AddEvent 还有另一种重载方法,但我不确定...

【问题讨论】:

  • 很快就会有!
  • 错误添加了错误的副本,如何删除?

标签: c#


【解决方案1】:

通常像 int 这样的简单类型不能为 null,使用 ?允许 int 像对象一样具有空值。

在函数内部,需要检查eventId是否有效才能使用。您可以通过检查 HasValue 或等于 null 来做到这一点。如果你尝试不检查就使用它,并且它为空,那么它会抛出 System.InvalidOperationException:

public string AddEvent(DateTime date, int eventCount, int? eventId, string eventGuid)
{
    // use HasValue
    if (eventId.HasValue)
        eventId++;

    // or check for null
    if (eventId != null)
        eventId++;
}

【讨论】:

    【解决方案2】:

    很简单,这不是 C++ 代码。它是 C#,其中? 表示nullable value type。 IE。一个值类型,也可以是nullint?Nullable<int> 的快捷方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-17
      • 1970-01-01
      • 2021-10-26
      • 2017-03-31
      • 2012-09-29
      • 2010-10-19
      相关资源
      最近更新 更多