types“string”必须是非空types,才能将其用作genericstypes或方法“System.Nullable <T>”中的参数T

为什么我得到错误“types'string'必须是一个不可为空的值types,以便将其用作通用types或方法'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; } } } } 

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

Nullable<T>types要求T是一个不可为空的值types,例如intDateTime 。 引用types如string可能已经为空。 允许Nullable<string>类的东西是没有意义的,所以它是不允许的。

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

 public class WordAndMeaning { public string Word { get; set; } public string Meaning { get; set; } } 

string是一个引用types,一个类。 你只能使用Nullable<T>T? 具有非空types的C#语法糖,如intGuid

特别是,由于string是引用types, stringtypes的expression式可能已经为空:

 string lookMaNoText = null; 

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

为了一个非常具体的原因,Type Nullable<int>把你的游标放在Nullable上,然后按下F12 – 元数据提供了原因(注意结构约束):

 public struct Nullable<T> where T : struct { ... } 

http://msdn.microsoft.com/en-us/library/d5x73970.aspx