C# 中的类(带有文件帮助程序)- 可空字符串在其他可空类型不存在时给出错误
我有一个类(由 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;
网上一些常见的讨论是通过字段等定义构造函数,但考虑到其他字段工作正常,字符串有什么特别之处?有没有一种优雅的方法来避免它?
I have a class (used by filehelpers) which gives me an error when I try to define a nullable string:
public String? ItemNum;
The error is:
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>'
This occurs even with the lowercase string
, though I haven't yet seen a difference between those.
Using another type such as int, decimal etc is fine:
public decimal? ItemNum;
Some general looking on the net talks about defining constructors by field etc, but given the other fields work fine, what's special about string? Is there an elegant way to avoid it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
string
是引用类型,引用类型本质上可以为空。当您定义
公共字符串 ItemNum
时,它已经可以为空。添加了
Nullable
结构,以允许值类型也可以为空。当你声明
公共十进制? ItemNum
,相当于public Nullable;项目编号
。Nullable
struct 有定义:where T : struct
表示T
只能是值类型。MSDN 中的描述非常详细Nullable Structure。
引用:
string
is reference type, reference types are nullable in their nature.When you define
public string ItemNum
, it is already nullable.Nullable
struct was added to allow make value types nullable too.When you declare
public decimal? ItemNum
, it is equivalent topublic Nullable<decimal> ItemNum
.Nullable
struct has definition:where T : struct
means thatT
can be only value type.Description in MSDN is very detailed Nullable Structure.
Quote: