我系统中的用户可以使用电子邮件,移动电话或电话,并根据传递的值检查某些条件,然后为每个条件设置ContactDataStatus(这是一个枚举)。然后我检查ContactDataStatus以确定提供的联系人详细信息是否有效。
枚举具有以下定义
public enum ContactDataStatus
{
ExistsButUnverified = 1,
ExisitsAndVerified = 2,
IsValid = 3,
IsUninitialized = 4
}
如果要设置isValid变量
的条件,我写了以下内容 isValid = false;
if (emailStatus == ContactDataStatus.IsValid &&
(mobileStatus == ContactDataStatus.IsValid ||
mobileStatus == ContactDataStatus.IsUninitialized)
&& (phoneStatus == ContactDataStatus.IsValid ||
phoneStatus == ContactDataStatus.IsUninitialized))
{
isValid = true;
}
else if (mobileStatus == ContactDataStatus.IsValid &&
(emailStatus == ContactDataStatus.IsValid ||
emailStatus == ContactDataStatus.IsUninitialized) &&
(phoneStatus == ContactDataStatus.IsValid ||
phoneStatus == ContactDataStatus.IsUninitialized))
{
isValid = true;
}
else if (phoneStatus == ContactDataStatus.IsValid &&
(emailStatus == ContactDataStatus.IsValid ||
emailStatus == ContactDataStatus.IsUninitialized) &&
(mobileStatus == ContactDataStatus.IsValid ||
mobileStatus == ContactDataStatus.IsUninitialized))
{
isValid = true;
}
是否有更简单/更短的写作方式?
答案 0 :(得分:6)
如果你告诉我们enum的价值是什么会有所帮助。听起来您希望至少有一个值是有效的,并且所有值都要未初始化或有效。所以表达的一种方式是:
var statuses = new[] { emailStatus, mobileStatus, phoneStatus };
bool valid = statuses.Any(x => x == ContactDataStatus.IsValid) &&
statuses.All(x => x == ContactDataStatus.IsValid ||
x == ContactDataStatus.IsUninitialized);
或者,如果状态枚举只是IsValid
,IsUninitialized
和(比方说)IsInvalid
,并且您知道实际的值将在该集合中,你可以写:
var statuses = new[] { emailStatus, mobileStatus, phoneStatus };
bool valid = statuses.Any(x => x == ContactDataStatus.IsValid) &&
statuses.All(x => x != ContactDataStatus.IsInvalid);
另外,我建议您删除" is"来自每个枚举值的前缀 - 它只会让代码更难以读取IMO。
答案 1 :(得分:0)
var statuses = new[] { emailStatus, mobileStatus, phoneStatus };
bool isValid = statuses
.Any(s => s == ContactDataStatus.IsValid && statuses.Except(new[] { s }).All(o => o == ContactDataStatus.IsValid || o == ContactDataStatus.IsUninitialized));