c# readonly const 区别
Const 静态的常量。 | Readonly |
和final java 一样概念 静态的常量。 常量定义:在编译时。运行时不可以修改。 必须定义成:成员变量。 常量必须是 integral 完整类型type ( | 动静态 都可以。 Class Instance 变量。的属性是可以修改的 Struct 的不是不可以 修改他的属性的。 readonly字段的赋值只能作为字段声明的组成部分出现,或在同一类中的实例构造函数或静态构造函数中出现。 一个只读成员,表现出 不可以被修改。 只读成员, 初始化 在运行时。。。 可以初始化 在 定义 或者 构造 or 注意 只读成员 不是 隐式的静态,但是可以用static 修饰。 readonly 关键字 可以用 复杂类型,可以用new 关键子 初始化。 readonly 不能是 enu 枚举类型。 |
const string sv = "abc" ; const float pii = 3.1415926f; const static string psss = "aaa"; // 默认就是的static 并且这样不行 const string sss = null; | readonly string rdstr = System.Windows.Forms.Application.StartupPath + "aaa"; Test() { // 构造函数。 rdstr = "s" + sv; } private static readonly string path = System.Windows.Forms.Application.StartupPath + "aaa"; |
想赋值都不行。 只能用null const Test testt = new Test(); Test.cs(122,24): error CS0134: “Acme.Collections.Test.testt”的类型为“Acme.Collections.Test”。只能用 null 对引用类型(字符串除外)的常量进行初始化 | Console.WriteLine( new Test().rdstr); /* Test.cs(142,27): error CS0120: 非静态的字段、方法或属性“Acme.Collections.Test.rdstr”要求对象引用 */ Console.WriteLine(path); |
static 变量 static 关键字修饰。 被访问 不是在 实例创建时候。 静态方法和属性访问 静态事件。 means that the member is no longer tied to a specific object.? The |
对于一个 readonly的 Reference类型,只是被限定不能进行赋值(写)操作而已。而对其成员的读写仍然是不受限制的。 public static readonly Class1 my = new Class1(); … my.SomeProperty = 10;//正常 my = new Class1(); //出错,该对象是只读的 但是,如果上例中的 Class1不是一个 Class而是一个 struct,那么后面的两个语句就都会出错。 static readonly中 static是当载入一个类时执行一次的。 C#中是怎么执行的,我没有查到。很奇怪几乎每本java的书都会说static的问题,C#的往往只说怎么用,但是应该是在main函数调用之前初始化,所以static readonly也是运行时的,可以用变量付值,如: private static readonly string path = System.Windows.Forms.Application.StartupPath + “aaa”; 引用下文: Java
http://www.blogjava.net/gddg/archive/2008/01/27/178070.html http://dev.youkuaiyun.com/develop/article/82/82998.shtm