C# - what does the unary ^ do?

前提是你 提交于 2020-08-10 01:46:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!