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

Syt*_*one 3 .net c# generics

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

例如


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

Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 8

你不能这样做,因为T没有任何意义IMyMainInterface.如果你的目标是让每个值是一个实现了一些 IMyInterface<T>,但每个值可能是不同的实现T,那么你或许应该声明一个基本接口:

public interface IMyInterface
{
    void SomeFunction();
}

public interface IMyInterface<T> : IMyInterface
{
    T Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后:

public interface IMyMainInterface
{
    Dictionary<string, IMyInterface> Parameters { get; }
}
Run Code Online (Sandbox Code Playgroud)

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

var pair = dictionary.First();
var value = pair.Value;
Run Code Online (Sandbox Code Playgroud)

什么类型可以value推断为?


但是,如果每个值应该相同 T,那么您只需要将其他接口设置为通用.为了更清楚,我重命名了type参数以保持Ts分离:

public interface IMyMainInterface<TFoo>
{
    Dictionary<string, IMyInterface<TFoo>> Parameters { get; }
}
Run Code Online (Sandbox Code Playgroud)