。NET平台中有a struct,我想将其用作类的状态。该结构是内置的,这一点很重要,因此我无法更改它。可以说,此内置结构是下面的ImmutableStruct
。
struct ImmutableStruct
{
public string Value { get; }
public ImmutableStruct(string value) { Value = value; }
}
我的类必须是线程安全的,因此状态必须声明为volatile
。当然,还有其他方法可以实现线程安全,但是可以说,对于特定情况,已选择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
:
boxing and unboxing
这是可行的,但是从对象进行转换会引起我的焦虑,因为该程序容易受到运行时错误的影响。我想要一个类型安全的解决方案,让编译器在编译时确保程序的正确性。所以我的问题是:有没有办法用安全类型对结构进行装箱和拆箱?
顺便说一句有关将结构标记为class MyClass
{
private volatile object _state = new ImmutableStruct("SomeString");
public ImmutableStruct State => (ImmutableStruct)_state;
/* Method that mutates the _state reference is omitted */
}
:volatile
的相关问题。我的问题之所以如此,是因为它专门针对装箱/拆箱操作的类型安全性。
如何创建这样的通用包装:
Volatile for structs and collections of structs