如何使结构不可变?

时间:2016-04-21 20:50:57

标签: c# struct immutability

遍布Stack Overflow和互联网我发现保持结构不可变是一个很好的设计原则。不幸的是,我从未看到任何实际导致这些结构真正不可变的实现。

假设一个struct里面没有任何引用类型,我该如何实际构造一个struct不可变?也就是说,如何防止任何原始字段的变异(可能是编译时/运行时异常)?

我编写了一个简单的测试,尝试使结构不可变,但甚至没有使用System.ComponentModel.ImmutableObjectAttribute工作:

class Program
{
    static void Main(string[] args)
    {
        ImmutableStruct immStruct1 = new ImmutableStruct();
        Console.WriteLine(immStruct1); //Before mutation.

        immStruct1.field1 = 1;
        immStruct1.field2 = "Hello";
        immStruct1.field3 = new object();
        Console.WriteLine(immStruct1); //After 1st mutation.

        immStruct1.field1 = 2;
        immStruct1.field2 = "World";
        immStruct1.field3 = new object();
        Console.WriteLine(immStruct1); //After 2nd mutation.

        Console.ReadKey();
    }
}

[ImmutableObject(true)]
struct ImmutableStruct
{
    public int field1;
    public string field2;
    public object field3;

    public override string ToString()
    {
        string field3String = "null";
        if (field3 != null)
        {
            field3String = field3.GetHashCode().ToString();
        }
        return String.Format("Field1: {0}, Field2: {1}, Field3: {2}", field1, field2, field3String);
    }
}

2 个答案:

答案 0 :(得分:16)

创建字段private readonly并在构造函数中传递初始值

public struct ImmutableStruct
{
    private readonly int _field1;
    private readonly string _field2;
    private readonly object _field3;

    public ImmutableStruct(int f1, string f2, object f3)
    {
        _field1 = f1;
        _field2 = f2;
        _field3 = f3;
    }

    public int Field1 { get { return _field1; } }
    public string Field2 { get { return _field2; } }
    public object Field3 { get { return _field3; } }
}

从C#6.0开始(Visual Studio 2015)您可以使用仅限getter属性

public struct ImmutableStruct
{
    public ImmutableStruct(int f1, string f2, object f3)
    {
        Field1 = f1;
        Field2 = f2;
        Field3 = f3;
    }

    public int Field1 { get; }
    public string Field2 { get; }
    public object Field3 { get; }
}

请注意,readonly fields和getter only属性可以在构造函数中初始化,也可以在类中使用字段或属性初始值设定项public int Field1 { get; } = 7;进行初始化。

无法保证构造函数在结构上运行。例如。如果您有一个结构数组,则必须为每个数组元素显式调用初始值设定项。对于引用类型数组,所有元素首先被初始化为null,这使得您必须在每个元素上调用new。但很容易忘记像结构这样的值类型。

var immutables = new ImmutableStruct[10];
immutables[0] = new ImmutableStruct(5, "hello", new Person());

从C#7.2开始,您可以使用Read-only structs

答案 1 :(得分:3)

将您的不可变数据保密:

struct ImmutableStruct
{
    private int field1;
    private string field2;
    private object field3;

    public ImmutableStruct(int f1, string f2, object f3)
    {
        field1 = f1;
        field2 = f2;
        field3 = f3;
    }

    public int Field1 => field1;
    public string Field2 => field2;
    public object Field3 => field3;
}

或者不那么杂乱:

struct ImmutableStruct
{
    public ImmutableStruct(int f1, string f2, object f3)
    {
        Field1 = f1;
        Field2 = f2;
        Field3 = f3;
    }

    public int Field1 { get; }
    public string Field2 { get; }
    public object Field3 { get; }
}