首页 > 解决方案 > 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。以上只是正在进行的工作。

标签: c#generics.net-corecontainers

解决方案


我正在使用与此类似的解决方案:

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; }
    }
}

推荐阅读