Readonly与Const
两者主要区别:
- const是编译常量,readonly是运行常量,效率高。因为const是变异常量,所以本来就是static,不能再用static修饰。
- const只能修饰基元类型、枚举,而readonly没有限制,灵活性强。
const
const变量之所以效率高,是因为编译器编译后,在代码引用const变量会用const变量所对应的实际值来代替
const int cint = 250;
const string cstring = "sbrb";
Console.WriteLine(cint);
Console.WriteLine(cstring);
readonly
readonly变量赋值是发生在运行的时候,readonly全部意义在于第一次运行时被赋值后将不可更改:
- 对于值类型变量,值本身不可改变
- 对于引用类型变量,引用本身也就是指针不可改变
值类型
ReadOnlySample readOnlySample = new ReadOnlySample("测试一");
//readOnlySample.ReadOnlyName="aga";//无法对只读字段赋值
var str = readOnlySample.ReadOnlyName;
public class ReadOnlySample
{
public readonly string ReadOnlyName;
public ReadOnlySample(string name)
{
ReadOnlyName = name;
}
}
引用类型
- 引用类型赋值后变量不能再指向其他实例。见实例1.
- 引用本身不可以变,但是引用所指实例的值可以改变。见实例2.
- readonly运行重要的意义在于,可以为每个类的实例指定一个readonly的变量。
实例1
ReadOnlySample readOnlySample = new ReadOnlySample(new Student() { Age = 12 ,Name="bebf"});
//无法对只读字段赋值
// readOnlySample.ReadOnlyS = new Student() { Age = 15, Name = "fbff" };
public class ReadOnlySample
{
public readonly Student ReadOnlyS;
public ReadOnlySample(Student name)
{
ReadOnlyS = name;
}
}
public class Student
{
public int Age { get; set; }
public string Name { get; set; }
}
实例2
ReadOnlySample readOnlySample = new ReadOnlySample(new Student() { Age = 12 ,Name="bebf"});
// readOnlySample.ReadOnlyS = new Student() { Age = 15, Name = "fbff" };
readOnlySample.ReadOnlyS.Name = "已经改变";
枚举
允许使用的枚举类型有byte、sbyte、short、ushort、int、uint、long、ulong。
将0值作为枚举的默认值、避免给枚举元素提供显示值
- 编译器会自动从0开始计数,然后逐个为元素的值+1,为避免错误应该将0作为枚举默认值,见例1
- 枚举元素允许设置重复值,应该避免给枚举值提供显示值,避免不同枚举有相同值
例1
例如以下,输出数据为0,不在枚举中的数据。
Console.WriteLine((Type)0);
public enum Type:byte
{
Thread=1,
AsemyThread,
Apex=2,
DoubleApex=3,
DoubleThread=4
}
例2
设置显示值后,AsemyThread没有赋值但自动计算后也为2,
Console.WriteLine((Type)2);
Console.WriteLine((byte)Type.AsemyThread);
Console.WriteLine((byte)Type.Apex);
Console.WriteLine(Type.AsemyThread.Equals(Type.Apex));
Console.WriteLine(Type.AsemyThread.CompareTo(Type.Apex));
本建议不适用于枚举类型指定System.FlagsAttribute属性,要求每个元素的值都是2的若干次幂。