首页 > 解决方案 > 如何对具有类型安全性的结构进行装箱和拆箱

问题描述

.NET 平台中有一个结构,我想将其用作我的类的状态。结构是内置的很重要,所以我无法更改它。可以说这个内置结构ImmutableStruct如下。

struct ImmutableStruct
{
    public string Value { get; }

    public ImmutableStruct(string value) { Value = value; }
}

我的类需要是线程安全的,所以必须声明状态volatile。当然还有其他方法可以实现线程安全,但可以说volatile已选择一个字段作为特定情况的最佳选择。所以我像这样对我的课程进行编码:

class MyClass
{
    private volatile ImmutableStruct _state = new ImmutableStruct("SomeString");
    // Error CS0677
    // 'MyClass._state': a volatile field cannot be of the type 'ImmutableStruct'

    public ImmutableStruct State => _state;

    /* Method that mutates the _state is omitted */
}

不幸的是,编译器不允许volatile结构字段。所以我决定使用装箱和拆箱

class MyClass
{
    private volatile object _state = new ImmutableStruct("SomeString");

    public ImmutableStruct State => (ImmutableStruct)_state;

    /* Method that mutates the _state reference is omitted */
}

这行得通,但是从对象进行强制转换让我感到焦虑,因为程序可能会遇到运行时错误。我想要一个类型安全的解决方案,编译器在编译时确保程序的正确性。所以我的问题是:有什么方法可以对具有类型安全性的结构进行装箱和拆箱?

顺便说一句,有一个关于将结构标记为的相关问题volatileVolatile for structs and collections of structs。我的问题在于它专门针对装箱/拆箱操作的类型安全。

标签: c#structthread-safetytype-safetyboxing

解决方案


如何创建这样的通用包装器:

public  class ReadonlyStructWrapper<T> where T: struct 
    {
        public T Value { get; }
        public ReadonlyStructWrapper(T value)
        {
            Value = value;
        }
    }

推荐阅读