我可以创建一个列表<类< T>>?创建一个、列表、GT、LT

2023-09-06 21:53:53 作者:你已经不是我的回忆了〃

我有一个类

public class Setting<T>
{
    public string name { get; set; }

    public T value { get; set; }
}

现在我想创建一个的IList&lt;设定&LT; T&GT;&GT; ,但不同类型的的设置&LT; T&GT; 的在里面T,我想要的eG

now I want to create an IList<Setting<T>> but with different types of Setting<T>'s T in it, I want e.G.

List<Setting<T>> settingsList;
settingsList.Add(new Setting<int>());
settingsList.Add(new Setting<string>()); 

我已经试过的IList&lt;设定&LT; T&GT;&GT; 但这似乎不可能的,因为编译器未找到类型 T

I've tried IList<Setting<T>> but this seems not possible since the compiler doesn't find Type T.

我知道,我可以使用对象,但我希望它是强类型。所以我的问题是,如果没有得到这个工作的可能性。

I know that I could use object but I want it to be strongly typed. So my question is if there is a possibility of getting this working.

推荐答案

泛型类型没有一个共同的类型或接口之间默认情况下具体的定义。

Generic types do not have a common type or interface amongst concrete definitions by default.

让你的设置&LT; T&GT; 类实现一个接口(或从通用类派生),并创建一个接口(或类)的列表

Have your Setting<T> class implement an interface (or derive from a common class) and create a list of that interface (or class).

public interface ISetting { }

public class Setting<T> : ISetting
{
    // ...
}

// example usage:
IList<ISetting> list = new List<ISetting>
{
    new Setting<int> { name = "foo", value = 2 },
    new Setting<string> { name = "bar", value "baz" },
};