Adding different types of shared objects to the general list

Can I add different types of shared objects to the list ?. As shown below.

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

and let's say that I have all these objects ...

 ValuePair<string> data1 =  new ValuePair<string>();
 ValuePair<double> data2 =  new ValuePair<double>();
 ValuePair<int> data3 =  new ValuePair<int>();

I would like to keep these objects in the general list. As

List<ValuePair> list = new List<ValuePair>();

list.Add(data1);
list.Add(data2);
list.Add(data3);

Is it possible?

+5
source share
4 answers

In general, you will have to either use List<object>or create a base class that is not generic, like

public abstract class ValuePair
{
    public string Name { get; set;}
    public abstract object RawValue { get; }
}

public class ValuePair<T> : ValuePair
{
    public T Value { get; set; }              
    public object RawValue { get { return Value; } }
}

Then you can have List<ValuePair>.

Now there is one exception: covariant / contravariant types in C # 4. For example, you can write:

var streamSequenceList = new List<IEnumerable<Stream>>();

IEnumerable<MemoryStream> memoryStreams = null; // For simplicity
IEnumerable<NetworkStream> networkStreams = null; // For simplicity
IEnumerable<Stream> streams = null; // For simplicity

streamSequenceList.Add(memoryStreams);
streamSequenceList.Add(networkStreams);
streamSequenceList.Add(streams);

This is not applicable in your case because:

  • You are using a generic class, not an interface
  • , T, "" "" API
  • , ( IEnumerable<int> IEnumerable<object>)
+11

, ValuePair ValuePair<T> : ValuePair ( ) List<object>. :

public abstract class ValuePair
{
    public string Name { get; set; }
    public object Value
    {
        get { return GetValue(); }
        set { SetValue(value); }
    }
    protected abstract object GetValue();
    protected abstract void SetValue(object value);
}
public class ValuePair<T> : ValuePair
{
    protected override object GetValue() { return Value; }
    protected override void SetValue(object value) { Value = (T)value; }
    public new T Value { get; set; }
}
+4

, . ValuePair, ValuePair<T>. .

+1

, .

:

List<ValuePair> list = new List<ValuePair>();

which you wrote in your example does not provide a specific type for T, and this is a problem, as soon as you pass it, you can only add an object of that particular type.

+1
source

All Articles