什么是&和&&运算符在C# [英] What is the diffrence between & and && operators in C#

查看:515
本文介绍了什么是&和&&运算符在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解&和&&运算符在C#中。我在互联网上搜索没有太多的成功。有人可以用范例解释吗?

I am trying to understand the difference between & and && operators in C#. I searched on the internet without much success. Can somebody please explain with an example?

推荐答案

& 按位AND运算符。对于整数类型的操作数,它将计算操作数的按位AND,结果将是一个整数类型。对于布尔操作数,它将计算操作数的逻辑和。 &&& 是逻辑AND运算符,不适用于整数类型。对于可应用两者的布尔类型,区别在于&& 的短路属性。如果&& 的第一个操作数计算为 false ,则第二个操作数不进行计算。这不是& 的情况:

& is the bitwise AND operator. For operands of integer types, it'll calculate the bitwise-AND of the operands and the result will be an integer type. For boolean operands, it'll compute the logical-and of operands. && is the logical AND operator and doesn't work on integer types. For boolean types, where both of them can be applied, the difference is in the "short-circuiting" property of &&. If the first operand of && evaluates to false, the second is not evaluated at all. This is not the case for &:

 bool f() {
    Console.WriteLine("f called");
    return false;
 }
 bool g() {
    Console.WriteLine("g called");
    return false;
 }
 static void Main() {
    bool result = f() && g(); // prints "f called"
    Console.WriteLine("------");
    result = f() & g(); // prints "f called" and "g called"
 }

|| 类似于此属性中的&&&

当然,用户定义的类型可以重载这些操作符,使他们做任何他们想做的任何事情。

Of course, user defined types can overload these operators making them do anything they want.

这篇关于什么是&和&&运算符在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆