c#中的类(带有文件助手) - 当其他可空类型不是时,可以为空的字符串给出错误

Gli*_*kot 4 .net c# generics filehelpers nullable

我有一个类(由filehelpers使用),当我尝试定义一个可空字符串时,它给出了一个错误:

public String? ItemNum;
Run Code Online (Sandbox Code Playgroud)

错误是:

 Error  1   The type 'string' must be a non-nullable value type in order 
 to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'
Run Code Online (Sandbox Code Playgroud)

即使使用小写字母也会出现这种情况string,尽管我还没有看到它们之间的区别.

使用其他类型,如int,decimal等是好的:

public decimal? ItemNum;
Run Code Online (Sandbox Code Playgroud)

一些关于网络的一般性讨论关于按字段等定义构造函数,但鉴于其他字段工作正常,字符串有什么特别之处?有一种优雅的方法可以避免它吗?

Ale*_*Aza 14

string 是引用类型,引用类型的性质可以为空.

定义时public string ItemNum,它已经可以为空.

Nullable 添加了struct以允许make值类型也可以为空.

当你声明时public decimal? ItemNum,它相当于public Nullable<decimal> ItemNum.

Nullable struct有定义:

public struct Nullable<T> where T : struct, new()
Run Code Online (Sandbox Code Playgroud)

where T : struct意味着T只能是值类型.

MSDN中的描述是非常详细的Nullable结构.

引用:

例如,诸如String之类的引用类型是可空的,而诸如Int32之类的值类型则不是.值类型不能为空,因为它具有足够的容量来仅表达适合该类型的值; 它没有表达null值所需的额外容量.