C#代码质量改善建议(四)——区别Readonly与Const、将0值作为枚举的默认值、避免给枚举元素提供显示值

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的若干次幂。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值