简体   繁体   中英

Class with generic type and generic list

I want to have a list of custom objects with a "generic" type in one of the properties.

public class Tag
{
    public string Name { get; set; }
    public int id { get; set; }

    public ??? value {get;set;}

}

The "value" can be int,double,string or bool.

How can I make a "generic" list of my custom Tag class?

public list<Tag> t;

I have looked the "generic" collections and classes, but the problem, is that if I made

class Tag<T>{}

I can not do:

List<Tag<T>> list = new List<Tag<T>>();
list.add(new Tag<int>());
list.add(new Tag<double>());

I have tried using interfaces, base classes ... I don't know where to look

Some ideas? help?

Thank you so much.

A common approach would be to make an interface or base class.

public interface ITag
{
    string Name { get; set; }
    int Id { get; set; }

    object Value { get; }
    Type ValueType { get; }
}

Then Tag can be generic:

public class Tag<T> : ITag
{
    public string Name { get; set; }
    public int Id { get; set; }

    public T Value { get; set; }

    object ITag.Value => this.Value;
    Type ITag.ValueType => typeof(T);
}

Now you can do this:

List<ITag> list = new List<ITag>();
list.Add(new Tag<int>());
list.Add(new Tag<double>());

The question is still why?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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