c# - C#:通过异构字典公开类型安全 API
问题描述
我想通过特定的 JSON 格式公开一个类型安全的 API。到目前为止,这基本上是我所拥有的:
public class JsonDictionary
{
Dictionary<string, Type> _keyTypes = new Dictionary<string, Type> {
{ "FOO", typeof(int) },
{ "BAR", typeof(string) },
};
IDictionary<string, object> _data;
public JsonDictionary()
{
_data = new Dictionary<string, object>();
}
public void Set<T>(string key, T obj)
{
if (typeof(T) != _keyTypes[key])
throw new Exception($"Invalid type: {typeof(T)} vs {_keyTypes[key]}");
_data[key] = obj;
}
public dynamic Get(string key)
{
var value = _data[key];
if (value.GetType() != _keyTypes[key])
throw new Exception($"Invalid type: {value.GetType()} vs {_keyTypes[key]}");
return value;
}
}
可以很好地用作:
JsonDictionary d = new JsonDictionary();
d.Set("FOO", 42);
d.Set("BAR", "value");
但是读取值有点令人失望,并且依赖于后期绑定:
var i = d.Get("FOO");
var s = d.Get("BAR");
Assert.Equal(42, i);
Assert.Equal("value", s);
是否有一些 C# 魔法可以用来实现类型安全的泛型Get<T>
而不是依赖dynamic
这里(理想情况下应该在编译时检查类型)?我还想使用该模式来Set<T>
触发d.Set("BAR", 56);
编译警告。
Dictionary<string, Type> _keyTypes
如果需要可以制作static
。以上只是正在进行的工作。
解决方案
我正在使用与此类似的解决方案:
public class JsonDictionary
{
public static readonly Key<int> Foo = new Key<int> { Name = "FOO" };
public static readonly Key<string> Bar = new Key<string> { Name = "BAR" };
IDictionary<string, object> _data;
public JsonDictionary()
{
_data = new Dictionary<string, object>();
}
public void Set<T>(Key<T> key, T obj)
{
_data[key.Name] = obj;
}
public T Get<T>(Key<T> key)
{
return (T)_data[key.Name];
}
public sealed class Key<T>
{
public string Name { get; init; }
}
}
推荐阅读
- sql-server - 如何在 SQL 语句中使用条件
- git - git pull --rebase 默默地忽略变基冲突
- r - 使用`lapply`重命名列表中的选定列
- python-3.x - 如何提高弹性搜索性能
- javascript - javascript 或 Jquery UI 中的可排序行
- stanford-nlp - 覆盖斯坦福 TokensRegex 的默认环境设置
- python - Tensorflow Queue 会加速单 CPU 机器上的数据加载吗?
- excel - 计算过滤结果并粘贴文本以计算数量
- android - ADB:如何通过 sendevent 以编程方式确定用于发送触摸事件的输入设备
- javascript - Javascript 空数组并用图像 BLOB 填充