Ref readonly 属性 类型 class

Ref readonly property with class type

我正在尝试创建只读 属性(c# 7.2 功能)。

public class JobStatus
{
    public int Id { get; set; }
}

public class Job
{
    public ref readonly JobStatus Status => ref _jobStatus;
    private readonly JobStatus _jobStatus = new JobStatus
    {
        Id = 4
    };
}

class Program
{
    static void Main(string[] args)
    {
        var job = new Job();
        job.Status.Id = 5;
    }
}

这段代码编译成功。我希望在尝试更新只读 属性 字段时出现某种错误。我是否错误地使用了 ref readonly return 功能?

根据我在this article中找到的内容,您应该理解如下

Marking a parameter as “readonly ref” or “in” does not make the value it refers to immutable. While the function declaring the parameter cannot make changes to it, the value can be changed elsewhere. This doesn’t require multiple-threads, just a way to access the original variable the parameter refers to.

因此,由于您的 class 不是一成不变的,因此可以在其他地方进行更改。此功能似乎主要是关于传递参考值的性能