gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:06:00 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com