C#中的常量有两种:
const
readonly
const在声明的时候就需要赋值,否则编译出错。
readonly可以不赋值,赋值的话只能在声明时(可以是静态变量或者常量),或者构造函数中赋值(可以是变量或者常量)。
看下边的例子:
?public class Class1 ??? { ??????? public const string YOURNAME = "MABOSI"; ??????? public readonly string myName = "BOSIMA"; ??????? public Class1() ??????? { ??????????? myName = "波斯马"; ??????? } ??????? public Class1(string name) ??????? { ??????????? myName = name; ??????????? //错误的 ??????????? YOURNAME = "321"; ??????? } ??????? //错误的: ??????? //readonly只能在声明时或构造函数中赋值 ??????? //const只能在声明时赋值 ??????? public void SetName(string name) ??????? { ??????????? myName = name; ??????????? YOURNAME = name; ??????? } ??? }
发表评论
相关文章
想了解服务发现、配置管理的同学,欢迎加入1000人Consul交流群:234939415
扫码关注公众号:萤火架构
文章分类
最新评论