简体   繁体   English

该方法返回的是真还是假?

[英]What will this method return, true or false?

bool isValid = false;
string username = "someadmin";

If( !String.IsNullOrEmpty(username) && !( username.IndexOf("admin") != -1)
    isValid = true;

The second part with the double negatives is crossing me up! 带有双重否定的第二部分让我生气了!

May I present to you DeMorgan's Laws : 我可以向您介绍摩根大通的法律

NOT (P OR Q) = (NOT P) AND (NOT Q)
NOT (P AND Q) = (NOT P) OR (NOT Q)

So, you could rewrite it as: 因此,您可以将其重写为:

if (!(String.IsNullOrEmpty(username) || username.IndexOf("admin") != -1)) {
    isValid = true;
}

...thus removing the double negatives. ...因此消除了双重负面影响。

Furthermore, you could say: 此外,您可以说:

if (String.IsNullOrEmpty(username) || username.IndexOf("admin") != -1) {
    isValid = false;
}

...which removes all the negatives. ...消除所有负面因素。

Also, you could say: 另外,您可以说:

isValid = !(String.IsNullOrEmpty(username) || username.IndexOf("admin") != -1));

...to make it nice and compact. ...使其美观小巧。

it will return false 它将返回false

!String.IsNullOrEmpty(username)          // this is true, the string is not NullOrEmpty
!(username.IndexOf("admin") != -1)       // IndexOf is >= 0, so != 1 is true. But the first ! makes it false

So IsValid will contain the same value as it had at the beginning... 因此IsValid将包含与开始时相同的值...

它将返回false。

A plain language version: 普通语言版本:

if (username is not null or empty and username doesn't contain "admin") isValid = true; 如果(用户名不为null或为空,并且用户名不包含“ admin”),则isValid = true;

isValid will be false. isValid将为false。

(Nitpick: this code doesn't "return" anything: it just sets the value of the isValid variable.) (Nitpick:此代码不“返回”任何内容:它只是设置isValid变量的值。)

false. 假。 But I don't get the question? 但是我不明白这个问题吗? Couldn't you just execute this? 你不能执行这个吗? What double negatives? 什么双重底片? The value is just being inverted and the parentheses clearly indicate the order in which the statements are executed. 该值只是被反转,并且括号清楚地指示了语句的执行顺序。

存储在isValid的值将为false

It will give you a syntax error due to a missing paren ;-) 由于缺少括号,它将给您语法错误;-)

But seriously, it will return false. 但是严重的是,它将返回false。

!String.IsNullOrEmpty(username) // if username is NOT null and NOT empty => true !String.IsNullOrEmpty(username)//如果用户名不为null且不为空=> true

username.IndexOf("admin") != -1 // if "admin" IS FOUND in username (not -1) => true username.IndexOf(“ admin”)!= -1 //如果在用户名中找到“ admin”(不是-1)=> true

!( username.IndexOf("admin") != -1 ) // if "admin" IS NOT FOUND in username => false !(username.IndexOf(“ admin”)!= -1)//如果未在用户名中找到“ admin” => false

So, concluding: the conditions of the if statement are NOT met, so isValid will remain false. 因此,结论是:不满足if语句的条件,因此isValid将保持为false。

PS.: I'm not ac# programmer, but I presume that when IndexOf(string) equals -1, it means not found. PS .:我不是ac#程序员,但我认为当IndexOf(string)等于-1时,表示找不到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM