Skip to main content
 首页 » 编程设计

c#之具有空安全性的 Web API 空列表

2024年01月22日27over140

我有一个 Angular Controller ,它可以发布到 Web API 方法。我试图在 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>();     
}