简体   繁体   English

泛型的通用列表

[英]A generic list of generics

I'm trying to store a list of generic objects in a generic list, but I'm having difficulty declaring it. 我正在尝试将通用对象列表存储在通用列表中,但我很难声明它。 My object looks like: 我的对象看起来像:

public class Field<T>
{
    public string Name { get; set; }
    public string Description { get; set; }
    public T Value { get; set; }

    /*
    ...
    */
}

I'd like to create a list of these. 我想创建一个这样的列表。 My problem is that each object in the list can have a separate type, so that the populated list could contain something like this: 我的问题是列表中的每个对象都可以有一个单独的类型,因此填充的列表可能包含这样的内容:

{ Field<DateTime>, Field<int>, Field<double>, Field<DateTime> }

So how do I declare that? 那么我该怎么宣布呢?

List<Field<?>>

(I'd like to stay as typesafe as possible, so I don't want to use an ArrayList). (我希望尽可能保持类型安全,所以我不想使用ArrayList)。

This is situation where it may benefit you to have an abstract base class (or interface) containing the non-generic bits: 这种情况下,拥有包含非泛型位的抽象基类(或接口) 可能会使您受益:

public abstract class Field
{
    public string Name { get; set; }
    public string Description { get; set; }
}

public class Field<T> : Field
{    
    public T Value { get; set; }

    /*
    ...
    */
}

Then you can have a List<Field> . 然后你可以有一个List<Field> That expresses all the information you actually know about the list. 这表达了您对列表实际了解的所有信息。 You don't know the types of the fields' values, as they can vary from one field to another. 您不知道字段值的类型,因为它们可能因字段而异。

Perhaps implement an interface. 也许实现一个接口。

interface IField
{
}

class Field<T> : IField
{
}

... ...

List<IField> fields = new List<IField>() { new Field<int>(), new Field<double>() };

You can't declare a list of generic types without knowing the generic type at compile time. 如果在编译时不知道泛型类型,则无法声明泛型类型列表。

You can declare a List<Field<int>> or a List<Field<double>> , but there is no other common base type for Field<int> and Field<double> than object . 可以声明一个List<Field<int>>List<Field<double>> ,但是不存在用于其它公共基类型Field<int>Field<double>object So the only List<T> that could hold different kinds of fields would be List<object> . 因此,唯一可以容纳不同类型字段的List<T>将是List<object>

If you want a more specific type for the list, you would have to make the Field<T> class inherit a class or implement an interface. 如果您希望列表具有更具体的类型,则必须使Field<T>类继承类或实现接口。 Then you can use that for the generic type in the list. 然后,您可以将其用于列表中的泛型类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM