问题
I have checked out some code and I got an error ('invalid expression term "^"' to be exact) in the line
// choices is a regular array
return choices[^1];
I have never seen a unary caret operator (I am only aware of the XOR operator, but that one obviously takes two operands). Does this operator exist and if so, what does it do?
Note: The site https://www.tutorialsteacher.com/csharp/csharp-operators mentions a unary caret operator in the precedence table but it does not explain what it does.
回答1:
Unary ^
is the "index from end" operator, introduced in C# 8.0. choices[^1]
is equivalent to choices[choices.Length - 1]
.
See the official documentation for additional details.
回答2:
In arrays it is called "Index from end operator" and is available from C# 8.0. As it says ... it indicates the element position from the end of a sequence.
In the second case, ^
plays the role of Logical exclusive OR operator. Being an operator, it needs to members (x ^ y
), because it is doing an operation on them.
As an example:
Console.WriteLine(true ^ true); // output: False
Console.WriteLine(true ^ false); // output: True
Console.WriteLine(false ^ true); // output: True
Console.WriteLine(false ^ false); // output: False
来源:https://stackoverflow.com/questions/60502615/c-sharp-what-does-the-unary-do