zoukankan      html  css  js  c++  java
  • C# 基础之const

    1、使用 const 关键字来声明某个常量字段或常量局部变量。常量字段和常量局部变量不是变量并且不能修改。 常量可以为数字、布尔值、字符串或 null 引用(Constants can be numbers, Boolean values, strings, or a null reference)。

    下面代码会报编译错误:

    public const DateTime myDateTime = new DateTime(2018,05,23,0,0,0);

    2、不允许在常数声明中使用 static 修饰符。

      static const string a = "a";  //Error

    报错:不能将变量“a”标记为static。

    3、常数可以参与常数表达式,如下所示:

    public const int c1 = 5;  
    public const int c2 = c1 + 100;

    4、readonly 关键字与 const 关键字不同:const 字段只能在该字段的声明中初始化。readonly字段可以在声明或构造函数中初始化。因此,根据所使用的构造函数,`readonly` 字段可能具有不同的值。

     1  class ReadOnly
     2     {
     3         private readonly string str;
     4         public ReadOnly()
     5         {
     6             str = @"ReadOnly() 构造函数";
     7             Console.WriteLine(str);
     8         }
     9         public ReadOnly(int i)
    10             : this()
    11         {
    12             str = @"ReadOnly(int i) 构造函数";
    13             Console.WriteLine(str);
    14             str = @"asd";
    15             Console.WriteLine(str);
    16         }
    17      }
    ReadOnly 构造函数初始化字符串

    调用:     ReadOnly ro = new ReadOnly(1);

    输出:

     5、static 

    如果 static 关键字应用于类,则类的所有成员都必须是静态的。不能通过实例引用静态成员。 然而,可以通过类型名称引用它。

    public class MyBaseC
    {
        public struct MyStruct
        {
            public static int x = 100;
        }
    }

    若要引用静态成员 x,除非可从相同范围访问该成员,否则请使用完全限定的名称 MyBaseC.MyStruct.x。

  • 相关阅读:
    xp系统优化
    项目开发文档格式13种 (转载)
    java 操作 ORACLE
    orclae temp table
    把EXCEL上传并BINDING到GRIDVIEW中
    从excel读数据写入数据库代码
    GMDatePicker控件的使用
    代码汇总
    dwr运行时出现Servlet.init() for servlet dwrinvoker threw exception的解决方法
    CVSNT安装
  • 原文地址:https://www.cnblogs.com/meng9527/p/9078525.html
Copyright © 2011-2022 走看看