100分拜上
解决方案 »
- dataGridView 控件如何分页啊
- botton事件为什么没触发弹出框
- 为什么我调用了SetCursorPos和mouse_event后,鼠标无反应.
- 为什么这样定义一个结构数组不行?
- 『请教』如何得到系统目录(%SystemRoot%)?
- asp.net(C#)项目经理 应该具备什么素质
- 怎么抢模式对话框的焦点
- 怎样用VC#做出一个类似《金山词霸》那样的非正规Windows界面?
- 怎样保存我在编辑器里的代码折叠?
- 求一个读取plt文件并显示的方法啊
- C#中有没有和VB的CTYPE()同样功能的类型转化函数
- 在制作安装包时 要求用户自己输入 SQL SERVER 的用户名和密码 请问如何对密码进行*****隐藏显示
C# 关键字 | 修饰符
const 关键字用于修改字段或局部变量的声明。它指定字段或局部变量的值不能被修改。常数声明引入给定类型的一个或多个常数。此声明采用的形式为:[attributes] [modifiers] const type declarators;
其中: attributes(可选)
可选的声明信息。有关属性和属性类的更多信息,请参见 C# 属性。
modifiers(可选)
包括 new 修饰符和四个访问修饰符之一的可选修饰符。
type
这些类型之一:byte、char、short、int、long、float、double、decimal、bool、string、枚举类型或引用类型。
declarators
以逗号分隔的声明符列表。声明符采取的形式为:
标识符 = 常量表达式 attributes 和 modifiers 适用于所有由常数声明声明的成员。常数声明的 type 指定声明引入的成员类型。常数表达式必须产生具有目标类型或者可隐式转换为目标类型的类型的值。常数表达式是在编译时可被完全计算的表达式。因此,对于引用类型的常数,可能的值只能是 string 和 null。备注
常数声明可以声明多个常数,例如:public const double x = 1.0, y = 2.0, z = 3.0;
不允许在常数声明中使用 static 修饰符。常数可以参与常数表达式,例如:public const int c1 = 5.0;
public const int c2 = c1 + 100;
示例
// const_keyword.cs
// Constants
using System;
public class ConstTest
{
class MyClass
{
public int x;
public int y;
public const int c1 = 5;
public const int c2 = c1 + 5; public MyClass(int p1, int p2)
{
x = p1;
y = p2;
}
} public static void Main()
{
MyClass mC = new MyClass(11, 22);
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
Console.WriteLine("c1 = {0}, c2 = {1}", MyClass.c1, MyClass.c2 );
}
}
输出
x = 11, y = 22
c1 = 5, c2 = 10
示例
该示例说明如何将常数用作局部变量。// const_keyword2.cs
using System;
public class TestClass
{
public static void Main()
{
const int c = 707;
Console.WriteLine("My local constant = {0}", c);
}
}
输出
My local constant = 707
注意 readonly 关键字与 const 关键字不同。const 字段只能在该字段的声明中初始化。readonly 字段可以在声明或构造函数中初始化。因此,根据所使用的构造函数,readonly 字段可能具有不同的值。另外,const 字段是编译时常数,而 readonly 字段可用于运行时常数,如下例所示:
public static readonly uint l1 = (uint) DateTime.Now.Ticks;
请参见
C# 关键字 | 修饰符--------------------------------------------------------------------------------向 Microsoft 发送有关此主题的反馈© Microsoft Corporation。保留所有权利。
t = new test( haha );
上面的这个写法有问题,const的东西是不能够在运行时初始化的。我想楼主大概是这个意思吧:
public static myDelegate mEvent = new myDelegate();
{
return;
}
public static readonly Action<int>[] gActions =
{
new Action<int>(MyAction0),
new Action<int>(MyAction1)
};public static void MyAction0(int n)
{
Console.WriteLine("A0");
}
public static void MyAction1(int n)
{
Console.WriteLine("A1");
} gActions[0](0);
gActions[1](0);
const 是只读
不一样
const int a = 10;
static int b = 10;
yourclass.a = 1000; //error
yourclass.b = 1000; //ok
c++ 可以修饰函数,单并不是说这个函数是只的,
一般有两种修饰方法
const int youfunct(); //返回一个只读变量
int youfunc() const //这个函数不能修改所在类的字段
c#不行,
因为作为函数来说都是只读的,动态的修改一个函数的代码,除非使用非常手段,static 静态,c#和C++差不多 意思是指这个方法或变量为所在类的实例共有,
const int a = 10;
static readonly int b = 10;
yourclass.a = 1000; //error
yourclass.b = 1000; //error
注意 readonly 关键字与 const 关键字不同。const 字段只能在该字段的声明中初始化。readonly 字段可以在声明或构造函数中初始化。因此,根据所使用的构造函数,readonly 字段可能具有不同的值。另外,const 字段是编译时常数,而 readonly 字段可用于运行时常数,如下例所示: