Two knowledge points in CSharpby luvex

Two grammer features: - const & readonly - ref & out

  • const & readonly

readonly 关键字与 const 关键字不同。 const 字段只能在该字段的声明中初始化。 readonly 字段可以在声明或构造函数中初始化。 因此,根据所使用的构造函数,readonly 字段可能具有不同的值。 另外,虽然 const 字段是编译时常量,但 readonly 字段可用于运行时常量,如此行所示:^[1]^

public static readonly uint l1 = (uint)DateTime.Now.Ticks;

In a word, const can be seen as a static constant, however, readonly can be seen as a dynamic constant which can be determined while the program is running.

  • ref & out

ref 关键字通过引用(而非值)传递参数。 通过引用传递的效果是,对所调用方法中的参数进行的任何更改都反映在调用方法中。 例如,如果调用方传递本地变量表达式或数组元素访问表达式,所调用方法会将对象替换为 ref 参数引用的对象,然后调用方的本地变量或数组元素将开始引用新对象。^[2]^ out 关键字通过引用传递参数。 这与 ref 关键字相似,只不过 ref 要求在传递之前初始化变量。 若要使用 out 参数,方法定义和调用方法均必须显式使用 out 关键字。^[3]^

``` class OutExample {

static void Method(out int i)

{

    i = 44;

}

static void Main()

{

    int value;     

    Method(out value); 

    // value is now 44     

} } ```

reference:

  1. msdn readonly

  2. msdn ref

  3. msdn out

Published 22 May 2015