C#中的" - "代表什么,以及它在VB中的作用

Wil*_*ill 1 c# vb.net visual-studio-2010

我有这个示例代码

public class MyClass
{
    private static int tempKey = 0;

    public MyClass()
    {
        this.Key = --tempKey;
    }
    public int Key {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

--tempkey究竟做了什么?

Mic*_*uda 10

它递减tempKey并返回新值.比较tempKey--,也减少tempKey,但返回原始值.

在此处查看Microsoft文档.

增量运算符(++)将其操作数增加1.增量运算符可以出现在其操作数之前或之后:

++ var 
var ++ 
Run Code Online (Sandbox Code Playgroud)

哪里:

var表示存储位置或属性或索引器的表达式.

第一种形式是前缀增量操作.操作的结果是操作数增加后的值.

第二种形式是后缀增量操作.操作的结果是操作数增加之前的值.

编辑:这对C#有效.Visual Basic没有此递增/递减运算符.

在Visual Basic中--tempKey被评估为-1 * (-1 * tempKey)等于tempKey.

在此输入图像描述


小智 6

" - x"是预递减算术运算符.意味着在语句中使用之前,该值减1.

int x = 10;
Console.WriteLine(--x); // This will print 9
Run Code Online (Sandbox Code Playgroud)

"x--"是后递减算术运算符.意味着使用该值然后减1.

int x = 10;
Console.WriteLine(x--); // This will print 10
Console.WriteLine(x):   // This will print 9
Run Code Online (Sandbox Code Playgroud)