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

C# 11中如何传递结构体值类型的引用?遇空引用异常

解决C# 11中结构体存储值类型引用的NullReferenceException问题

你的代码触发异常的核心原因是ref字段赋值时未传递引用。_number是ref double类型字段,存储的是对值的引用,但构造函数里直接写_number = number,实际是把参数的值而非引用赋给了未初始化的引用目标,因此触发NullReferenceException。

修复方案

修改构造函数的赋值语句,添加ref关键字明确传递引用:

using System.Runtime.CompilerServices;

var x = 1.1;
var myTuple = new CustomRef(ref x);

x = 2.2;

Console.WriteLine(x); // 输出 2.2
Console.WriteLine(myTuple.GetNumber()); // 输出 2.2

public ref struct CustomRef
{
    private readonly ref double _number;

    public CustomRef(ref double number)
    {
        // 关键修改:添加ref关键字传递引用
        _number = ref number;
    }

    public double GetNumber()
    {
        if (Unsafe.IsNullRef(ref _number))
        {
            throw new InvalidOperationException("数值引用字段未初始化。");
        }

        return _number;
    }
}

额外说明

  • ref struct的ref字段必须保证引用目标的生命周期不短于结构体本身,比如示例中局部变量x和结构体myTuple在同一作用域,不会出现悬空引用问题。
  • readonly ref字段表示字段的引用本身不可修改,但可以读取(甚至修改)引用目标的值(只要目标本身不是readonly类型)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:10:24