我看到代码是这样的:
double d = GetDouble();
DoSomething(+d);
DoSomething(-d);
Run Code Online (Sandbox Code Playgroud)
我知道这有潜在的危险,并且不建议在 C++ 中使用一元+来强调该值是正数。<EDIT>“只是强调价值是积极的”是一条心理捷径。我知道它不会使负值变为正值。</EDIT>
C #语言参考并没有对此说太多:
一元 + 运算符返回其操作数的值。
SO 上有一个关于此的问题,但它被标记为 C、C++ 和 C#,并且没有一个答案明确提到 C#。
正如您链接的问题的答案所说,C+ (++) 中的一元确实做了一些事情,并且不一定是无操作。在 C# 中也是如此。
C# 只有这些一元+运算符(请参阅规范):
int operator +(int x);
uint operator +(uint x);
long operator +(long x);
ulong operator +(ulong x);
float operator +(float x);
double operator +(double x);
decimal operator +(decimal x);
Run Code Online (Sandbox Code Playgroud)
因此,如果x是 a short,+x则属于 类型int,因为第一个运算符是通过重载决策选择的。结果,像这样的东西无法编译:
short x = 1;
short y = +x;
Run Code Online (Sandbox Code Playgroud)
除其他外,这还会影响重载解析。就像这个答案中提供的代码一样,如果您这样做:
public class C {
public static void Foo(int x) {
Console.WriteLine("int");
}
public static void Foo(short x) {
Console.WriteLine("short");
}
}
Run Code Online (Sandbox Code Playgroud)
C.Foo(x)其中xa shortwill print short, but C.Foo(+x)will print int。
像上面这样的情况是否经常发生,导致+x“不好”或“不安全”的做法?这由你决定。
当然,如果x是自定义结构/类类型,那么+x基本上可以做任何事情。一元+是可重载的。