c# - c# 中的类(使用 filehelpers)- 可空字符串在其他可空类型不存在时给出错误

标签 c# .net generics nullable filehelpers

我有一个类(由 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/

相关文章:

c# - 如何在 C# 中访问对象?

c# - 如何以编程方式查找用于签署给定证书的证书?

c# - MVC3 应用程序中的通用 "back"按钮

c# - Unity CS0308 错误

.net - 如何在 asp :DataGrid for CSS? 中的第一个表头上放置一个 ID

java - 为什么我不能在接收参数化参数的方法中使用通配符?

c# - 泛型和匿名类型

ios - 关联类型 Swift 3

c# - MVVM和从模型到 View 模型的隐式转换

c# - "Operation could destablize the runtime"和具有值类型的 DynamicMethod