Collection of generic types

前端 未结 9 821
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 21:06

If I have a generic class:

public class MyClass 
{
  public T Value;
}

I want to instantiate several items such as...



        
9条回答
  •  日久生厌
    2020-11-27 21:16

    The only way I can think of, off the top of my head is as follows (wrapped up in a Console app for testing):

    class Program
    {
        static void Main(string[] args)
        {
            var x = new MyClass() { Value = "34" };
            var y = new MyClass() { Value = 3 };
    
            var list = new List();
            list.Add(x);
            list.Add(y);
    
            foreach (var item in list)
            {
                Console.WriteLine(item.GetValue);
            }
        }
    
        private interface IMyClass
        {
            object GetValue { get; }
        }
    
        private class MyClass : IMyClass
        {
            public T Value;
    
            public object GetValue
            {
                get
                {
                   return Value;
                }
            }
        }
    }
    

    i.e. Have MyClass implement an empty interface and then create your collections as one that holds instances of classes that implement that interface.

    Update: I've added a "GetValue" method to the interface that allows you to access the "Value" of the MyClass instance as an Object. This is about as good as it's going to get, afaik, if you want to have a collection that holds mixed types.

提交回复
热议问题