小编tri*_*nha的帖子

如何使 C# 类的 Object 属性可选?

我正在尝试在 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'

请向我解释上述情况并为我提供替代解决方案。

.net c# nullable non-nullable

2
推荐指数
1
解决办法
8557
查看次数

标签 统计

.net ×1

c# ×1

non-nullable ×1

nullable ×1