为了在通用类型或方法"Nullable< T>"中将其用作参数"T",类型"MyObject"必须是不可为空的值类型.

为了在通用类型或方法

问题描述:

我正在使用.net framework 4.5

我收到以下错误

错误CS0453类型'MyObject'必须是不可为空的值类型,以便将其用作通用类型或方法'Nullable'中的参数'T'

Error CS0453 The type 'MyObject' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable'

  public async Task<Nullable<MyObject>> MyMethod(string myParamter)
    {}

我也尝试过

  public async Task<MyObject?> MyMethod(string myParamter)
    {}

如果我将其设置为可为空,那么为什么出现此错误消息的情况下方法名称下方的红线

If I set the thing as nullable then why do I get the red line below the method name with this error message

*

The * answer is easy, make the return type nullable but for me Visual studio doesn't allow it.

由于MyObject是一个对象,并且对象根据定义可以为空,因此按顺序使用Nullable<T> struct或?运算符是没有用的支持空值.

Since MyObject is an object, and objects are nullable by definition, there is no use to use the Nullable<T> struct or ? operator in order to support null values.

Nullable<T>用于结构(例如DateTime)和值类型(例如intfloat等).

Nullable<T> is for structs (like DateTime) and value types like int, float, etc.