tri*_*nha 2 .net c# nullable non-nullable
我正在尝试在 C# 中创建一个模型类,其中我需要对象/列表属性作为可选属性:
public class Customer
{
[JsonProperty("Custid")]
public string CustId { get; set; }
[JsonProperty("CustName")]
public string CustName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
public class Store
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("Name")]
public string? Name { get; set; }
[JsonProperty("Customer")]
public List<Customer>? Customers{ get; set; } *//Error 1*
[JsonProperty("OtherProperty")]
public object? OtherProperty{ get; set; } *//Error 2*
}
Run Code Online (Sandbox Code Playgroud)
上面的代码给出的错误为:-
错误 1:类型“对象”必须是不可为空的值类型,才能将其用作泛型类型或方法“可空”中的参数“T”
错误 2:类型“ List' 必须是不可为 null 的值类型,以便将其用作泛型类型或方法 'Nullable' 中的参数 'T'
请向我解释上述情况并为我提供替代解决方案。
string,List和object都是引用类型。默认情况下,它们可以为空。的Nullable类型(例如int?为简写Nullable<int>)仅用于值类型。
在 C# 8.0 中,引入了一项新功能,该功能允许不可为空的引用类型 - 即明确禁止空值分配的引用类型。这是一个选择加入功能 - 您可以启用它以允许您更清楚地显示有关参考的意图。如果使用它,则用于定义可空引用类型的语法与可空值类型的语法相同:
string nonNullableString = null; // Error
string? nullableString = null; // Ok
Run Code Online (Sandbox Code Playgroud)
请记住,启用不可为空的引用类型意味着所有没有跟在后面的引用类型都是?不可为空的;这可能需要您对应用程序进行大量更改。
所以有你的两个选择。要么启用不可为空的引用类型,然后您需要显式标记您希望可以为空的类型,要么坚持使用可为空的引用类型,并且只使用string而不是string?用于相同的结果。我鼓励默认情况下使用不可为 null 的类型,因为它有望避免一整类非常常见的编程错误。
| 归档时间: |
|
| 查看次数: |
8557 次 |
| 最近记录: |