C Sharp/变量与常量

常量 编辑

常量就是在程序运行期间维持不变的量,常量也有类型。

字面常量 编辑

字面常量就是书写在代码中固定的数值。

using System;

public class Demo
{
    public static void Main()
    {
        Console.WriteLine(12);
    }
}

其中数字12就是字面常量,其类型为int型。

符号常量 编辑

变量 编辑

C#中的字段(fields), 形参(parameters),局部变量(local variables)都对应于变量。

字段即类级变量、类的数据成员。又分为“实例变量”(instance variable)与静态变量。常值字段要求声明时就该赋值。字段的可见性修饰从高到低:public, protected, internal, protected internal, private

局部变量分为常值(存放在assembly data region)与非常值(存放在栈中)。在声明的作用域中可见。

方法的形参:

  • in修饰,是缺省情况。对于值类型(int, double, string)为“传值”,对于引用类型为“传引用”。
  • out修饰,被编译器认为直到方法调用这个名字是非绑定(unbound)的。因此在方法内未赋值就引用输出参数是非法的。方法内部的正常执行路径必须对输出参数赋值。
  • reference修饰,为方法调用前已经bound。方法内部不是必须赋值。
  • params修饰,表示可变参数。必须是形参表最后一个。
// Each pair of lines is what the definition of a method and a call of a 
//   method with each of the parameters types would look like.
// In param:
void MethodOne(int param1)    // definition
MethodOne(variable);          // call

// Out param:
void MethodTwo(out string message)  // definition
MethodTwo(out variable);            // call

// Reference param;
void MethodThree(ref int someFlag)  // definition
MethodThree(ref theFlag)            // call

// Params
void MethodFour(params string[] names)           // definition
MethodFour("Matthew", "Mark", "Luke", "John");   // call