在c# 中static 和const的区别

来源:百度知道 编辑:UC知道 时间:2024/05/25 08:38:02
如题 用static 修饰 函数
const 是固定 好像意思有点接近
还有在定义整体变量的时候也用到这2个关键词

static为静态修饰符,可以放在对象前面(函数也是一种对象)如:
class Example{
public static void show(){
Console.WriteLine("这是一个静态方法");
}
}
可直接Example.show();去调用这个方法而不用实例化
当然也可以定义静态的属性:
public static string str="hello";
但如果这样Example.str="helloworld";就出现问题了
也就是客户端可以在任何地方去改变str的值。这样的话极容易产生错误,因为str的值是依靠Example类的,随时可以改变。比如再声明一个类:
Class Class1
{
Example.str="helloworld";
public void show()
{
Console.WriteLine(Example.str);//此时Example.str会输出helloworld
}
}
class Example{
public static string str="hello";
}
}
要防止str值发生改变,就需要用到const修饰符
public const string str="hello";//str被称为常量
这是如果再对Example.str赋值,则编译器将产生错误
用常量来保存公共数据是最为合适的。

static 是静态的意思 const 这个是定义常量的就是不能改变的意思

static运行时分配资源
const编译时分配