只有键类型已知的键值对集合

Collection of key-value pairs where only key type is known

我想要一个键值对集合class,我在实例化级别知道键类型,但在向集合添加新元素时我只知道值类型。

考虑下面的代码片段

public class Collection<TKey> where TKey : class
{
    public ICollection<KeyValuePair<TKey, IValue>> Col { get; set; }

    public void Add<TValue>(TKey key, TValue value) where TValue : IValue
    {
        Col.Add(new KeyValuePair<TKey, IValue>(key, value));
    }
}

public interface IValue
{
}

这很好用,但是,上面代码的问题是插入类型必须是 IValue 类型,因为基元不是 IValue 的实现者,所以它们不能添加到列表。

我不能用 object 代替 TValue / IValue

编辑

我想用任何一个!键值对的值参数的类型。如果可能的话,我想去掉 IValue。这是我编译代码的唯一方法

理想用法示例如下:

    collection.Add("hello", 10);
    collection.Add("peter", "temp");
    collection.Add("hello1", new Foo());
    collection.Add("hello2", new Bar());

编辑 我不能使用对象,因为对象不是所有对象都是可序列化的,但是,我将实现更改为

class Program
{
    static void Main(string[] args)
    {
        var collection = new Collection<string>();
        collection.Add("hello", 10);
        collection.Add("peter", "temp");
        collection.Add("hello", new Bar());
    }
}

[Serializable]
public class KeyValuePair<TKey, TValue>
{
    private TKey _key;
    private TValue _value;

    public KeyValuePair(TKey key, TValue value)
    {
        _key = key;
        _value = value;
    }

    public TKey Key
    {
        get { return _key; }
        set { _key = value; }
    }

    public TValue Value
    {
        get { return _value; }
        set { _value = value; }
    }
}

public class Collection<TKey> where TKey : class
{
    public ICollection<KeyValuePair<TKey, ISerializable>> Col { get; set; }

    public void Add<TValue>(TKey key, TValue value) where TValue : ISerializable
    {
        Col.Add(new KeyValuePair<TKey, TValue>(key, value));
    }
}

编译器说 argument type <TKey, TValue> is not assignable to parameter type <TKey, ISerializable>

如果您希望您的值包含基本类型,例如 int、float 等和自定义类型,那么您应该使用对象而不是 IValue。

public class Collection<TKey> where TKey : class
{
    public ICollection<KeyValuePair<TKey, object>> Col { get; set; }

    public void Add(TKey key, object value)
    {
        Col.Add(new KeyValuePair<TKey, object>(key, value));
    }
}

此外,如果您希望在运行时快速进行基于哈希的键查找,您可能希望将 ICollection<...> 更改为简单的 Dictionary<TKey, object>

事先注意:作为个人喜好,我倾向于使用字典来表示 key/value 对唯一键或 multimap/ilookup 当我需要重复键输入时。


如果您使用 C# 3.5 或更早版本,您可以使用

var dic = new Dictionary<string, object>();  

假设您使用的是 C# 4,您可以使用

var dic = new Dictionary<string, dynamic>();  

人们喜欢用它来存储 JSON 数据等。


你可以用 Rx-Linq 做很多事情,但我想指出你可以写:

var dic = new Dictionary<string, Lazy<string>>();

您可以在其中存储生成字符串的脚本。