我有一个类(由 filehelpers 使用),当我尝试定义可为 null 的字符串时它会给我一个错误:
public String? ItemNum;
错误是:
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>'
即使是小写的 string
也会出现这种情况,尽管我还没有发现它们之间的区别。
可以使用其他类型,例如 int、decimal 等:
public decimal? ItemNum;
网上的一些普通人谈论按字段等定义构造函数,但考虑到其他字段工作正常,string 有什么特别之处?有没有一种优雅的方式来避免它?
最佳答案
string
是引用类型,引用类型本质上是可以为空的。
当您定义 public string ItemNum
时, 它已经可以为 null。
Nullable
添加了结构以允许使值类型也可以为空。
当你声明public decimal? ItemNum
, 相当于 public Nullable<decimal> ItemNum
.
Nullable
结构有定义:
public struct Nullable<T> where T : struct, new()
where T : struct
意味着 T
只能是值类型。
MSDN中的描述很详细Nullable Structure .
引用:
For example, a reference type such as String is nullable, whereas a value type such as Int32 is not. A value type cannot be nullable because it has enough capacity to express only the values appropriate for that type; it does not have the additional capacity required to express a value of null.
关于c# - c# 中的类(使用 filehelpers)- 可空字符串在其他可空类型不存在时给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6366811/