Skip to main content
 首页 » 编程设计

c#之将 null 替代方法传递给重载

2024年02月23日17yyy_WW

有没有办法在 C# 中将空值传递给参数?

原因是我必须将一些 sql 参数作为空值(默认值在存储过程中设置)传递给我的 SQL 数据库中的一些存储过程。我背后的代码是通过数据访问类接收数据。因此,我必须在数据访问类中进行大量方法重载以支持事件/方法背后的代码。例如;

public static DataTable GetUsers(int companyId, int departmentId){ 
   //Return a DataTable of users in the given company & dept 
} 
public static DataTable GetUsers(int companyId){ 
   //Return a DataTable of users in the given company 
} 

如果我可以将 null 值传递给 departmentId,我可以避免这种重载并让 sp 处理它。

干杯!!

请您参考如下方法:

您可以使用可选参数,但是您需要使用 int? ( Nullable<int> 而不是 int ):

public static DataTable GetUsers(int companyId, int? departmentId = null){ 
   //Return a DataTable of users in the given company & dept 
}