Unity C# const与static readonly的区别与联系
1 using System; 2 3 namespace Test 4 { 5 class MainClass 6 { 7 //懒人写法的单例 8 class Weapon 9 { 10 public static readonly Weapon Instance; 11 static Weapon() 12 { 13 Instance=new Weapon(); 14 } 15 } 16 class MyWeapon 17 { 18 //static readonly和const的区别 19 public const int Speed=50;//const必须赋值,且只能用这种方法赋值 20 //static readonly 可以赋值也可以不赋值,也可以在用static修饰的构造方法中赋值 21 public static readonly int Speed_1; 22 public static readonly int Speed_2=50; 23 public static readonly int Speed_3; 24 static MyWeapon() 25 { 26 Speed_3=50; 27 } 28 } 29 30 public static void Main (string[] args) 31 { 32 //static readonly和const的联系, 33 //在外边只能通过类名.访问,且在外部不能赋值(二者都是只读的) 34 Console.WriteLine (MyWeapon.Speed_3);//50 35 } 36 } 37 }
博客园Jason_c微信打赏码
如果本篇文档对你有帮助,打赏Jason_c根华子吧,他的私房钱被老婆没收了,呜呜!