我有一个数据库结构( Entity Framework 模型),看起来像这样:
Business <-1----*-> Users <-*----0..1-> Role
非常简单明了: 企业可以拥有用户。 用户必须属于企业。 用户可能与某个角色相关,也可能不相关。 一个角色可以与许多用户相关。
在服务器的 API 级别,我想实现允许以下方法服务的功能:
//get all users
List<User> GetUsers();
//get all users belong to a business
List<User> GetUsers(int businessId);
//get all users with specific role
List<User> GetUsers(int roleId);
//get all users belong to a business with specific role
List<User> GetUsers(int businessId, int roleId);
但是我不希望在带有可选参数/命名参数的单个方法中编写我想要编写的内容的 4 个重载,所以 我想创建以下服务方法,而不是这 4 个:
List<Users> GetUsers(
int?? businessId=undefined, int?? roleId=undefined)
{
var queryResult = new List<users>();
if(!businessId.IsUndefined)
queryResult= {get from db all business according to Id.}
if(!roleId.IsUndefined)
queryResult = queryResult.Where(item=>user.role.Id==roleId)
}
现在你想知道“??”这个东西是怎么回事..
好吧,假设我想要获取与角色关系为 0 的所有用户。 - 这将返回一个特定的标准。
现在,假设我想要获取所有用户,无论角色关系如何。 - 这将返回不同的标准。
但是命名参数只能为 Nullable 以支持该行为:
List<Users> GetUsers(int? RoleId=null)
{
// is this null becuase it was not specified or is it null because
// it was called with null as argument.
// I need to know the difference to give the correct criteria.
// But I cannot tell the difference from within here...
// as in here it is simply null or some value.
}
所以这里有一个解决方案,我希望 int 不仅仅是可以为空, 我也希望它是不可定义的..并且我可以设置一个方法,如下所示:
List<Users> GetUsers(int?? RoleId=undefined)
因此,int?? 将是以下任何一个示例:
int?? x = 未定义;
int?? x = 空;
int?? x=5;
问题是 - 这可能吗? 我可以创建一些允许“int??”的东西吗?定义...
如果是这样 - 我该怎么做? 如果不是 - 如何克服这个问题?
最佳答案
也许您可以使用“业务”和“角色”的包装类,但定义隐式类型转换。这些类型转换将允许您的 API 用户向您发送一个 int
或一个 Role.Undefined
,或者然后向您发送 null。
例如,Role 类看起来像这样:
public class Role
{
private bool _isUndefined;
private int _val;
private Role()
{
_isUndefined = true;
}
private Role(int val)
{
_val = val;
}
public static Role Undefined
{
get { return new Role(); }
}
public static implicit operator Role(int val)
{
return new Role(val);
}
}
那么你的签名将如下所示:
List<User> GetUsers(Business business = null, Role role = null);
您的用户可以这样调用它:
GetUsers(Business.Undefined, Role.Undefined);
或者
GetUsers(1, 2);
或者
GetUsers(role: 8);
关于C# 如何通过方法中的可选参数解决这个困境?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25538482/