C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > c# const和static使用

C#的const和static的定义和核心区别

作者:垂葛酒肝汤

这篇文章主要介绍了C#中的const和static关键字的区别和使用场景,在Unity开发中,需要注意const和static的区别,避免内存泄漏和序列化问题,感兴趣的朋友跟随小编一起看看吧

1.定义:

const:

// 正确:编译期确定的固定值
public const string PlayerTag = "Player"; 
public const float DefaultMoveSpeed = 5.0f;
// 错误:Vector3是引用类型,且依赖Unity运行时API,编译期无法确定值
// public const Vector3 DefaultSpawnPos = Vector3.zero; 
// 错误示例:方法的默认值必须是编译时常量,
// 报错就说明vector3是一个引用类型,不能作为默认值
public int GetDistance(Vector3 pos = Vector3.one)
{
    return (int)pos.magnitude;
}

static:

// 单例(最常见场景)
public class GameManager : MonoBehaviour
{
    public static GameManager Instance; // 静态实例,全局访问
    void Awake() => Instance = this;
}
// 静态工具方法(无需实例,全局调用)
public static class MathTool
{
    public static float ClampSpeed(float speed) => Mathf.Clamp(speed, 0, 10);
}

2.const vs static 核心区别

对比维度const(编译时常量)static(静态成员)
赋值时机编译期确定,声明时必须赋值运行期初始化(静态构造函数),可延迟赋值
可修改性完全不可修改(编译后固化)可修改(除非加static readonly
数据类型限制仅支持基础值类型(int/float/string 等)支持所有类型(值类型 / 引用类型,如 GameObject)
Unity API 兼容性不兼容(无法引用 Unity 运行时 API,如 Vector3)兼容(可引用任意 Unity API)
内存特性无内存分配(编译期嵌入代码)内存中唯一副本,直到程序域销毁(游戏退出)
序列化无序列化(编译期常量,Unity 不处理)Unity 默认不序列化静态字段(Inspector 不可见)

3.Unity 开发中的关键注意事项

1. 易混淆点:const vs static readonly

2. static 的核心坑点(Unity 面试高频)

4.什么时候用 const,什么时候用 static?

到此这篇关于C#的const和static的问题的文章就介绍到这了,更多相关C# const和static内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文