TOC

This article is currently in the process of being translated into Chinese (~7% done).

The Basics:

Variables

变量可以看做一块存储空间,是编程中很重要的概念,在C#中,可以像这样定义变量:

<变量类型> <变量名>;

如下是一个定义变量的例子:

string name;

这是最基础的方式,但是此时变量没有值。你可以之后赋值,也可以像这样在声明变量时赋值:

<data type> <name> = <value>;

如果这个变量不是你正在使用的方法的局部变量(比如它是一个类的成员)。你可能希望设置变量的可见性:

<可见性> <变量类型> <变量名> = <值>;

如下是一个完整的例子:

private string name = "John Doe";

可见性的部分和类相关,你可以在类的章节中找到完整的解释。我们继续变量的话题,下面这个例子使用了多个变量:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string firstName = "John";
            string lastName = "Doe";

            Console.WriteLine("Name: " + firstName + " " + lastName);

            Console.WriteLine("Please enter a new first name:");
            firstName = Console.ReadLine();

            Console.WriteLine("New name: " + firstName + " " + lastName);

            Console.ReadLine();
        }
    }
}

这个例子的大部分已经解释过了,我们直接看有意思的部分。首先,我们定义了几个string类型的变量,string类型包含文本,如你所见,我们用文本直接对其赋值。接下来,我们向控制台输出了一行文本,这其中用到了两个变量。这个字符串是由 + 号连接的不同部分组成的。

接下来,我们要求用户输入一个名字, 然后用ReadLine()方法从控制台中读取用户输入并给firstName变量赋值。当用户按下回车键时,新的名字赋值到变量中,下一行我们再次输出名字来展示变化。我们已经使用了我们第一个变量和变量的最重要的特性:在运行时改变其值。

另一个有趣的例子是做数学运算,接下来是一个和上一个例子有很多相同代码的例子:

int number1, number2;

Console.WriteLine("Please enter a number:");
number1 = int.Parse(Console.ReadLine());

Console.WriteLine("Thank you. One more:");
number2 = int.Parse(Console.ReadLine());

Console.WriteLine("Adding the two numbers: " + (number1 + number2));

Console.ReadLine();

尝试把这个放到我们的Main方法中。唯一的新“技巧”是int.Parse()方法。它读取一个字符串并转化为一个整型。如你所见,这个应用没有验证用户输入,如果你的输入不是一个数字,将会发生一个异常。这些将在之后讨论。

Variables & scope

So far, we have only used local variables, which are variables defined and used within the same method. In C#, a variable defined inside a method can't be used outside of this method - that's why it's called local. If you're familiar with other programming languages, you may also know about global variables, which can be accessed from more places, but C# doesn't support the concept of global variables. Instead, you can define a field on a class, which can be accessed from all the methods of this class. Allow me to demonstrate this with an example:

using System;

namespace VariableScope
{
    class Program
    {
        private static string helloClass = "Hello, class!";

        static void Main(string[] args)
        {
            string helloLocal = "Hello, local!";
            Console.WriteLine(helloLocal);
            Console.WriteLine(Program.helloClass);
            DoStuff();
        }

        static void DoStuff()
        {
            Console.WriteLine("A message from DoStuff: " + Program.helloClass);
        }
    }
}

Notice the helloClass member, declared on the class scope instead of inside a method - this will allow us to access it from both our Main() method as well as our own DoStuff() method. That is not true for our helloLocal variable, which has been declared inside the Main() method and can therefore only be used inside of this specific method.

The concept of differentiating between where a variable has been declared is called scoping and it prevents your code from becoming a huge mess of variables which can be changed from too many places. Another technique that helps us with this is called member visibility (in this case illustrated with the private keyword), which we'll discuss in the chapter about classes.

Summary

Variables allow you to store data of various types, e.g. text strings, numbers or custom objects. There are local variables, which are accessible inside of the method in which it has been defined, and then there are class fields, which can be accessed from all the methods of the class and even outside of the class, if the visibility permits it.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!