Csharp/CSharp Tutorial/Class/readonly
Содержание
Creating a read-only property.
using System;
public class ClassWithReadOnlyProperty {
int fAge;
public int Age {
get {
return fAge;
}
}
public ClassWithReadOnlyProperty() {
fAge = 21;
}
}
class MainClass {
static public void Main() {
ClassWithReadOnlyProperty crp = new ClassWithReadOnlyProperty();
Console.WriteLine("Age {0}", crp.Age);
}
}
Readonly and const
public class MyClass
{
public MyClass()
{
this.y = 4;
this.y = 6;
SetField( ref this.y );
}
private void SetField( ref int val )
{
val = 8;
}
public readonly int x = 123;
public readonly int y;
public const int z = 555;
}
public class MainClass{
static void Main()
{
MyClass obj = new MyClass();
System.Console.WriteLine( "x = {0}, y = {1}, z = {2}",
obj.x, obj.y, MyClass.z );
}
}
x = 123, y = 8, z = 555
Readonly Fields
class Color
{
public Color(int red, int green, int blue)
{
this.red = red;
this.green = green;
this.blue = blue;
}
int red;
int green;
int blue;
public static readonly Color Red;
public static readonly Color Green;
public static readonly Color Blue;
static Color()
{
Red = new Color(255, 0, 0);
Green = new Color(0, 255, 0);
Blue = new Color(0, 0, 255);
}
}
class MainClass
{
static void Main()
{
Color background = Color.Red;
}
}
static readonly fields
public class Bicycle
{
public readonly string make;
public static readonly int wheels = 4;
public Bicycle(string make)
{
System.Console.WriteLine("Creating a Bicycle object");
this.make = make;
}
}
class MainClass
{
public static void Main()
{
System.Console.WriteLine("Bicycle.wheels = " + Bicycle.wheels);
Bicycle myBicycle = new Bicycle("AAA");
System.Console.WriteLine("myBicycle.make = " + myBicycle.make);
}
}
Bicycle.wheels = 4 Creating a Bicycle object myBicycle.make = AAA
Use readonly
You can create a read-only field in a class by declaring it as readonly.
A readonly field can be initialized, but not changed after that.
using System;
class MainClass {
public static readonly int SIZE = 10;
public static void Main() {
int[] nums = new int[MainClass.SIZE];
// MainClass.SIZE = 100; // Error!!! can"t change
}
}