&有什么区别?和&& C#中的运算符 [英] What is the difference between & and && operators in C#

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

问题描述

我试图理解C#中& & 运算符之间的区别。我在互联网上搜索失败。有人可以举个例子吗?

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

推荐答案

& 是按位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"
 }

|| 与该属性中的&& 类似;

|| is similar to && in this property; it'll only evaluate the second operand if the first evaluates to false.

当然,用户定义的类型可以使这些运算符超载,从而使其可以执行所需的任何操作。

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

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

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