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;
??????? }
??? }
发表评论
相关文章
国内AI资源汇总,AI聊天、AI绘画、AI写作、AI视频、AI设计、AI编程、AI音乐等,国内顺畅访问,无需科学上网。
扫码或点击进入:萤火AI大全
文章分类
最新评论