类型'string'必须是非可空类型才能在泛型类型或方法'System.Nullable <T>'中将其用作参数T.

Mis*_*ser 167 c# nullable

为什么我会得到错误"类型'字符串'必须是不可为空的值类型才能在泛型类型或方法'System.Nullable'中将它用作参数'T'?"

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using Universe;

namespace Universe
{
    public class clsdictionary
    {
      private string? m_Word = "";
      private string? m_Meaning = "";

      string? Word { 
          get { return m_Word; }
          set { m_Word = value; }
      }

      string? Meaning { 
          get { return m_Meaning; }
          set { m_Meaning = value; }
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 202

使用string,而不是string?在你的代码的所有地方.

Nullable<T>类型要求T是不可为空的值类型,例如intDateTime.类似的引用类型string已经可以为null.允许这样的东西Nullable<string>是不允许的,这是没有意义的.

此外,如果您使用的是C#3.0或更高版本,则可以使用自动实现的属性来简化代码:

public class WordAndMeaning
{
    public string Word { get; set; }
    public string Meaning { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

  • M.Babcock,当我做 m_Word = null 时,它出错了,有什么建议吗?我希望能够将 Word 设置为空。 (2认同)

Jon*_*eet 52

string是一个引用类型,一个类.您只能使用Nullable<T>T?C#语法糖与非可空类型,如intGuid.

特别是,作为string引用类型,类型的表达式string可以已经为null:

string lookMaNoText = null;
Run Code Online (Sandbox Code Playgroud)


Cha*_*ert 14

System.String已经可以为空了:你不需要声明它(string?myStr)是错误的.


ANe*_*own 5

请注意,在即将发布的 C# 版本 8 中,答案是不正确的。

All the reference types are non-nullable by default 您实际上可以执行以下操作:

public string? MyNullableString; 
this.MyNullableString = null; //Valid
Run Code Online (Sandbox Code Playgroud)

然而,

public string MyNonNullableString; 
this.MyNonNullableString = null; //Not Valid and you'll receive compiler warning. 
Run Code Online (Sandbox Code Playgroud)

这里重要的是显示代码的意图。 如果“意图”是引用类型可以为空,则对其进行标记,否则将空值分配给不可为空会导致编译器警告。

更多信息