c# - 如何对具有类型安全性的结构进行装箱和拆箱
问题描述
.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 */
}
这行得通,但是从对象进行强制转换让我感到焦虑,因为程序可能会遇到运行时错误。我想要一个类型安全的解决方案,编译器在编译时确保程序的正确性。所以我的问题是:有什么方法可以对具有类型安全性的结构进行装箱和拆箱?
顺便说一句,有一个关于将结构标记为的相关问题volatile
:Volatile for structs and collections of structs。我的问题在于它专门针对装箱/拆箱操作的类型安全。
解决方案
如何创建这样的通用包装器:
public class ReadonlyStructWrapper<T> where T: struct
{
public T Value { get; }
public ReadonlyStructWrapper(T value)
{
Value = value;
}
}
推荐阅读
- android - Android Webview:较小的显示尺寸会破坏布局
- javascript - 在 django html 模板中使用导航栏在 div 中安装 mapbox div
- angular - 无法读取多重中未定义错误的属性“长度”中的错误
- reactjs - React 在多个 Reactstrap 按钮之间切换活动类
- bash - 给定两个日期之间的时间差(以秒为单位)
- javascript - 我如何使这个游戏中的跳跃更顺畅。这是传送
- c# - 如何配置 asp.net kestrel 以实现低延迟?
- c++ - C ++解释赋值中的大括号?
- html - 用于文章反应的语义 HTML
- azure - 使用 spark 订阅事件中心时出现异常