ZetCode

C# 变量

最后修改于 2023 年 7 月 5 日

C# 变量教程展示如何在 C# 中使用变量。 C# 教程 是一个关于 C# 语言的综合教程。

变量 是一个存储位置。一个变量有一个名称和一个数据类型。数据类型决定了可以赋给变量的值,例如整数、字符串或布尔值。在程序运行期间,变量可以获得相同数据类型的各种值。

在可以引用变量之前,变量总是被初始化为其类型的默认值。

变量名必须遵守有效的 C# 标识符的规则。 变量名必须以字母或 _ 开头。 它们可以包含 Unicode 字母字符、十进制数字字符、Unicode 连接字符、Unicode 组合字符或 Unicode 格式化字符。 变量名区分大小写。

C# 变量示例

在第一个示例中,我们定义了几个变量。

Program.cs
string city = "Berlin";
string name = "Peter"; int age = 36;
string nationality = "German";

Console.WriteLine(city);
Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(nationality);

city = "London";
Console.WriteLine(city);

在该示例中,我们有四个变量。

string city = "Berlin";

我们声明一个字符串类型的 city 变量,并将其初始化为“New York”值。

string name = "Peter"; int age = 36;

我们声明并初始化了另外两个变量。 我们可以将两个语句放在一行上。 但为了便于阅读,每个语句应该单独成行。

Console.WriteLine(city);
Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(nationality);

我们将变量的值打印到终端。

city = "London";

我们为 city 变量赋一个新值。

$ dotnet run
Berlin
Peter
36
German
London

C# 变量 - var 关键字

可以使用 var 关键字隐式地键入变量。 这些变量始终是强类型的,但使用 var 时,类型由 C# 编译器从赋值的右侧推断出来。

Program.cs
var name = "Lucia";
var age = 27;

Console.WriteLine($"{name} is {age} years old");

name = "Robert";
age = 42;

Console.WriteLine($"{name} is {age} years old");

Console.WriteLine(name.GetType());
Console.WriteLine(age.GetType());

在该示例中,我们有两个隐式类型的变量。

var name = "Peter";
var age = 23;

在赋值的左侧,我们使用 var 关键字。 name 变量是 string 类型,age 变量是 int 类型。 类型是从赋值的右侧推断出来的。

Console.WriteLine(name.GetType());
Console.WriteLine(age.GetType());

我们使用 GetType 确定变量的类型。

$ dotnet run
Lucia is 27 years old
Robert is 42 years old
System.String
System.Int32

C# 局部变量

局部变量是一个变量,其作用域在其声明的块内。 局部变量可以在函数、try 语句、switch 语句或 for 和 foreach 语句中定义。

Program.cs
Console.WriteLine(Repeat(0, "hey"));
Console.WriteLine(Repeat());
Console.WriteLine(Repeat(4));
Console.WriteLine(Repeat(5, "cau"));

string Repeat(int times = 0, string message = "")
{
    int _times = 3;
    string _message = "hello";

    if (times == 0 && string.IsNullOrEmpty(message)) {

        return string.Join(" ", Enumerable.Repeat(_message, _times));
    } else if (times == 0 && !string.IsNullOrEmpty(message)) {

        return string.Join(" ", Enumerable.Repeat(message, _times));
    } else if (times != 0 && string.IsNullOrEmpty(message)) {

        return string.Join(" ", Enumerable.Repeat(_message, times));
    } else if (times != 0 && !string.IsNullOrEmpty(message)) {

        return string.Join(" ", Enumerable.Repeat(message, times));
    } else {

        return String.Empty;
    }
}

在该示例中,我们定义了两个局部变量:_times_message。 它们的有效性受到 Repeat 函数的花括号的限制。

$ dotnet run
hey hey hey
hello hello hello
hello hello hello hello
cau cau cau cau cau

C# 实例变量

实例变量存在于所创建类的实例中。 当没有更多对该实例的引用时,它将不复存在。

每个实例变量在每个创建的对象中都是唯一的。

Program.cs
var u1 = new User { Name = "John Doe", Occupation = "gardener" };
Console.WriteLine(u1);

var u2 = new User { Name = "Roger Roe", Occupation = "accountant" };
Console.WriteLine(u2);

class User
{
    public User() {}

    public string Name { set; get; }
    public string Occupation { set; get; }

    public override string ToString()
    {
        return $"{Name} is a(n) {Occupation}";
    }
}

我们有 User 类,它有两个实例变量:NameOccupation。 这两个变量在创建的两个类实例中是不同的。

$ dotnet run
John Doe is a(n) gardener
Roger Roe is a(n) accountant

C# 静态变量

静态变量值在类的所有实例之间共享。 无论创建了多少个类的实例,都只有一个静态成员的副本存在。

Program.cs
var counter1 = new Counter();
counter1.f();
counter1.f();
counter1.f();

var counter2 = new Counter();
counter2.f();
counter2.f();
counter2.f();

var ret1 = counter1.show();
var ret2 = counter2.show();

Console.WriteLine(ret1);
Console.WriteLine(ret2);

class Counter
{
    static int count = 0;

    public void f()
    {
        count++;
    }

    public string show() {

        return $"# of calls: {count}";
    }
}

我们有一个 count 静态成员变量,在 Counter 类中定义。 计数器通过 f 方法递增。

var counter1 = new Counter();
counter1.f();
counter1.f();
counter1.f();

我们创建一个 counter 对象并调用 f 方法三次。

var counter2 = new Counter();
counter2.f();
counter2.f();
counter2.f();

我们创建另一个 counter 对象并调用它的 f 方法三次。

$ dotner run
$ of calls: 6
$ of calls: 6

从输出中我们可以看到,两个对象共享静态 count 变量。

C# 变量 - 函数参数

值参数在调用其所属的函数、成员函数或匿名函数时产生。 它使用调用中给出的参数值进行初始化。

Program.cs
int r = Add(5, 6);
Console.WriteLine(r);

int r2 = Add(11, 12);
Console.WriteLine(r2);

int Add(int x, int y) {

    return x + y;
}

在该示例中,我们有两个函数参数:xy。 它们在 Add 函数的范围内有效。

$ dotnet run
11
23

C# 变量 - 函数引用参数

使用 ref 修饰符声明的参数是引用参数。 引用参数不会创建新的存储位置;它表示与作为参数给出的变量相同的存储位置。

Program.cs
int x = 5;
int y = 6;

Console.WriteLine(x);
Console.WriteLine(y);

Change(ref x, ref y);

Console.WriteLine("--------------------");

Console.WriteLine(x);
Console.WriteLine(y);


void Change(ref int x, ref int y) {

    x = 15;
    y = 16;
}

Change 函数中,现在没有创建新的变量。 而是传递对现有 xy 变量的引用。

$ dotnet run
5
6
--------------------
15
16

来源

声明语句 - 语言参考

在本文中,我们使用了 C# 中的变量。

作者

我叫 Jan Bodnar,是一位充满热情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直撰写编程文章。 迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 C# 教程