immutability - 如何检查 NET 5 中的 c# 9 中的记录在运行时是不可变的

标签 immutability record .net-5 c#-9.0

记录是 c#9、Net 5 中的新功能

这是 said

If you want the whole object to be immutable and behave like a value, then you should consider declaring it as a record

在 c#9、NET 5 中创建记录:

public record Rectangle
{
    public int Width { get; init; }
    public int Height { get; init; }
}

然后实例化它:

var rectangle = new Rectangle (20,30);

尝试更改值:

rectange.Width=50; //compiler error

编译器引发错误:

error CS8852: Init-only property or indexer 'Rectangle.Width' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.

这是正确的,并确保记录是不可变的。

使用方法like要测试 IsImmutable 类型,请给出 false,因为记录中没有生成只读属性。

如何检查 c# 9、Net 5 中的记录在运行时是不可变的,甚至它具有 init 属性

最佳答案

记录在运行时确实是可变的。这是故意的,这是否意味着大多数序列化器框架无需更新即可工作。

但是可以通过以下检查来检查属性是否为 initonly:

public static bool IsInitOnly(PropertyInfo propertyInfo)
{
    return propertyInfo?.SetMethod.ReturnParameter
        .GetRequiredCustomModifiers()
        .Any(x => x.FullName == _isExternalInitName)
        ?? false;
}

private static string _isExternalInitName =
    typeof(System.Runtime.CompilerServices.IsExternalInit).FullName;

关于immutability - 如何检查 NET 5 中的 c# 9 中的记录在运行时是不可变的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63934918/

相关文章:

java - 100% 不可变,但仍然不是线程安全的

iOS 如何在录音时在扬声器中播放提示音

c# - 尝试在 .Net5 中发布时出现 Nuget 错误

c# - 是否可以从另一个类库中的静态类获取 ConnectionString?

java : Question regarding immutable and final

swift - 不可变的 `var` 数组

ios - [__NSCFArray insertObject :atIndex:]: mutating method sent to immutable object'

Erlang - 列表推导式 - 填充记录

ios - 使用Linphone SDK时音频录制失败

c# - 如何启用 C# 9.0-preview