Web API 具有 Null 安全性的空列表
Web API Empty List With Null Safety
我有一个 angular 控制器,它对 Web API 方法执行 post。我试图在 ienumerable 上添加 null 安全性,但是当我这样做时导致 ienumerable 始终为空。
angular 通话
$http.post(customer/DoSomething, {names: ["chris", "joe"]})
方法
string DoSomething(Customer customer){...}
型号
// populates IEnumerable
public class Customer
{
public IEnumerable<string> Names {get; set;}
}
// what I want to do but IEnumerable is always empty
public class Customer
{
private IEnumerable<string> _names;
public IEnumerable<string> Names
{
get
{
return _names ?? new List<string>();
}
set
{
_names = value;
}
}
}
您可以添加一个构造函数来初始化您的集合。
// populates IEnumerable
public class Customer
{
public Customer()
{
this.Names = new List<string>();
}
public IEnumerable<string> Names {get; set;}
}
它将确保您的 Names
集合不为空。
编辑
现在已使用 C# 自动属性对此进行了简化
// populates IEnumerable
public class Customer
{
public IEnumerable<string> Names {get; set;} = new List<string>();
}
Sameer 的回答是最佳实践。
只是指出您的初始代码的问题,它总是返回 List 的一个新实例,因为您从未设置字段值。
public IEnumerable<string> Names
{
get
{
if(_names == null)
_names = new List<string>();
return _names;
}
set
{
_names = value;
}
}
我有一个 angular 控制器,它对 Web API 方法执行 post。我试图在 ienumerable 上添加 null 安全性,但是当我这样做时导致 ienumerable 始终为空。
angular 通话
$http.post(customer/DoSomething, {names: ["chris", "joe"]})
方法
string DoSomething(Customer customer){...}
型号
// populates IEnumerable
public class Customer
{
public IEnumerable<string> Names {get; set;}
}
// what I want to do but IEnumerable is always empty
public class Customer
{
private IEnumerable<string> _names;
public IEnumerable<string> Names
{
get
{
return _names ?? new List<string>();
}
set
{
_names = value;
}
}
}
您可以添加一个构造函数来初始化您的集合。
// populates IEnumerable
public class Customer
{
public Customer()
{
this.Names = new List<string>();
}
public IEnumerable<string> Names {get; set;}
}
它将确保您的 Names
集合不为空。
编辑
现在已使用 C# 自动属性对此进行了简化
// populates IEnumerable
public class Customer
{
public IEnumerable<string> Names {get; set;} = new List<string>();
}
Sameer 的回答是最佳实践。
只是指出您的初始代码的问题,它总是返回 List 的一个新实例,因为您从未设置字段值。
public IEnumerable<string> Names
{
get
{
if(_names == null)
_names = new List<string>();
return _names;
}
set
{
_names = value;
}
}