C#:通过异构字典公开类型安全 API [英] C#: Exposing type safe API over heterogeneous dictionary

查看:26
本文介绍了C#:通过异构字典公开类型安全 API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过特定的 JSON 格式公开类型安全的 API.到目前为止,这基本上是我所拥有的:

I'd like to expose a type safe API over a particular JSON format. Here is basically what I have so far:

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");

但是读取值有点令人失望并且依赖于后期绑定:

However reading the value is a little disapointing and rely on late binding:

var i = d.Get("FOO");
var s = d.Get("BAR");
Assert.Equal(42, i);
Assert.Equal("value", s);

是否有一些 C# 魔法可以用来实现类型安全的泛型 Get<T> 而不是在这里依赖 dynamic(理想情况下应该在编译时间)?我还想使用 Set 的模式,以便 d.Set("BAR", 56); 触发编译警告.

Is there some C# magic that I can use to implement a type-safe generic Get<T> instead of relying on dynamic here (ideally type should be checked at compilation time) ? I'd like to also use the pattern for Set<T> so that d.Set("BAR", 56); triggers a compilation warning.

字典<字符串,类型>如果需要,_keyTypes 可以设为 static.以上只是正在进行中.

Dictionary<string, Type> _keyTypes can be made static if needed. The above is just work in progress.

推荐答案

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

I was using solution similar to this:

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

这篇关于C#:通过异构字典公开类型安全 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆