通用字典,其值为具有通用引用的接口

时间:2010-11-01 15:59:55

标签: c# .net generics

我想要一个字典,其中值是通用对象,并且对于字典中的每个值都不相同。怎么能这样做,我觉得我错过了一些简单的事情。

EG


    public interface IMyMainInterface
    {
        Dictionary<string, IMyInterface<T>> Parameters { get; }
    }

    public interface IMyInterface<T>
    {
        T Value
        {
            get;
            set;
        }

        void SomeFunction();
    }

Result:
dic.Add("key1", new MyVal<string>());
dic.Add("key2", new MyVal<int>());

1 个答案:

答案 0 :(得分:8)

你不能这样做因为TIMyMainInterface中没有意义。如果您的目标是将每个值作为 some IMyInterface<T>的实现,但每个值可能是不同T的实现,那么您应该声明一个基接口:

public interface IMyInterface
{
    void SomeFunction();
}

public interface IMyInterface<T> : IMyInterface
{
    T Value { get; set; }
}

然后:

public interface IMyMainInterface
{
    Dictionary<string, IMyInterface> Parameters { get; }
}

编辑:鉴于您更新的问题,看起来这就是您要做的事情。如果您想知道为什么您必须这样做,请考虑如果您能够使用原始代码,将如何尝试使用字典中的值。想象:

var pair = dictionary.First();
var value = pair.Value;

value推断为什么类型?


但是,如果每个值都应该是相同的 T,那么您只需要使其他接口也是通用的。为了更清楚,我重命名了type参数以保持Ts分开:

public interface IMyMainInterface<TFoo>
{
    Dictionary<string, IMyInterface<TFoo>> Parameters { get; }
}