我正在开发一个自定义验证器,如果电子邮件地址或用户名没有更改,则需要失败。 基本上如果其中一个字符串比较为真那么它将通过验证。我知道我忽视了一些简单的事情。以下是我到目前为止的情况:
bool emailChanged = Domain.Validation.ItemsHaveChanged(txtEmailAddress.Text, emailAddress);
bool userNameChanged = Domain.Validation.ItemsHaveChanged(txtUserName.Text, userName);
// make sure at least the email or username has changed.
if (!emailChanged || !userNameChanged)
{
args.IsValid = false;
cvAccountChange.ErrorMessage = "There haven't been any changes to the account.";
}
以下是方法ItemsHaveChanged
public static bool ItemsHaveChanged(string param1, string param2)
{
return string.Compare(param1.Trim(), param2.Trim()) != 0;
}
答案 0 :(得分:4)
您正在寻找logical AND operator (&&
):
if (!emailChanged && !userNameChanged)
{
args.IsValid = false;
cvAccountChange.ErrorMessage = "There haven't been any changes to the account.";
}
答案 1 :(得分:1)
就个人而言,我避免了这种情况,只是这样做:
if (emailChanged || usernameChanged) {
// everything is fine
return;
}
// neither changed
args.IsValid = false;
...
也就是说,假设您可以从方法中提前返回。 (除此之外,你总是可以将那段代码剪切成一个单独的代码。)
或者,您可以避免早期返回和复杂的表达式:
var emailUnchanged = !ItemsHaveChanged(...);
var usernameUnchanged = !ItemsHaveChanged(...);
if (emailUnchanged || usernameUnchanged) {
// neither changed
args.IsValid = false;
...
}