该字段为实例字段时,在包含readonly字段声明的类的实例构造器中;或者,该字段为静态字段时,在包含readonly字段声明的静态构造器中。这是能把readonly字段作为out和ref参数传递的唯一情况。
在构造其中赋值。
using System;namespace readonly关键字{ internal class PRogram { private static void Main() { var myClass = new MyClass(); Console.WriteLine("number1 = {0} , number2 = {1} , number3 = {2} , number4 = {3} , number5 = {4}", myClass.Number1, myClass.Number2, MyClass.Number3, myClass.Number4, myClass.Number5); Console.ReadKey(); } } internal class MyClass { public readonly int Number1 = 100;//在声明时赋值 public readonly int Number2; public static readonly int Number3; public readonly int Number4 = 400; public readonly int Number5 = 500; static MyClass() { Number3 = 300; } public MyClass() { Number2 = 200;//在构造器中赋值 ChangeValue(out Number4,ref Number5); ChangeValue1(Number4, Number5);//值没有改变 } public void ChangeValue(out int p1, ref int p2) { p1 = 401; p2 = 501; } public void ChangeValue1(int p1,int p2) { p1 = 402; p2 = 502; } }}新闻热点
疑难解答