You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity C#中如何声明可读写的变量别名?

C# 实现可读写变量别名的两种方案

方案1:标准可读写属性(兼容性最好)

你原写法用的是仅带get的表达式体属性,补充set访问器即可实现读写能力,写法如下:

struct Data
{
    // 需调整字段访问修饰符,保证外层Instance可访问
    public int value;
}

class Instance
{
    private Data data;
    // 可读写属性,所有读写操作直接映射到内部data的value字段
    public int Value
    {
        get => data.value;
        set => data.value = value;
    }
}

使用方式和普通变量完全一致:

var ins = new Instance();
ins.Value = 10; // 写入等价于直接修改ins.data.value
Debug.Log(ins.Value); // 读取等价于直接读取ins.data.value

该方案兼容所有支持C# 6.0及以上的Unity版本,覆盖绝大多数现有项目。

方案2:Ref返回属性(更接近C++引用效果)

如果你需要更贴近C++引用的能力(比如将别名作为ref/out参数传递给方法),可以用C# 7.0引入的ref返回属性:

struct Data
{
    public int value;
}

class Instance
{
    private Data data;
    // 直接返回data.value的内存引用,所有操作直接作用于原字段
    public ref int Value => ref data.value;
}

除了常规读写外,还支持作为ref参数传递:

var ins = new Instance();
ins.Value = 10;

// 示例方法:接收ref参数修改原值
void AddOne(ref int num) => num += 1;
AddOne(ref ins.Value); // 执行后ins.Value会变为11

该方案要求Unity 2020.1及以上版本(默认支持C# 7.3),老版本可在Player Settings中手动调整脚本运行时版本为.NET 4.x即可兼容。

内容的提问来源于stack exchange,提问作者Owen Millward

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 06:48:02