简体   繁体   中英

Generic class and choosing an underlying collection for the collection fields

I would like to do something like this:

public class SomeClass<T> where T: ICollection
{
    public T<double> ListOfDoubles { get; set; }
    public T<int> ListOfIntegers { get; set; }
}

However, the problem I have is ICollection needs a type argument How do I get around this problem? I couldn't find the exact answer, probably I didn't formulate my search well enough.

You can just do this -

public class MyClass
{
  public ICollection<double> ListOfDoubles { get; set; }
}

It seems like what youre trying to do is ensure that the properties of this class are an ICollection, but you dont need to specify that in this case.

If you want to ensure that your property is a generic enumerable type you can do so by just specifying that it is an IEnumerable of double. Or if you want to ensure it is a type of ICollection then you can also just declare your property as -

public ICollection<double> ListOfDoubles {get;set}

Even if the compiler allowed you to do what you are doing you wouldnt gain anything because you can just declare the property as an ICollection yourself, it is already generic type.

It is better to create your own collection and customize it according to your personal taste.

Then use this Collection for your applications. The following code shows how to do this and you can add any method you want

 public class SimpleCollection<T> : ICollection<T>
{

   ICollection<T> _items;


   public SimpleCollection()
   {
       // Default to using a List<T>.
        _items = new List<T>();
   }

   protected SimpleCollection(ICollection<T> collection)
   {
      // Let derived classes specify the exact type of ICollection<T> to wrap.
      _items = collection;
   }

   public void Add(T item)
   {
       _items.Add(item);
   }

   public void Clear()
   {
       _items.Clear();
   }

   public bool Contains(T item)
   {
       return _items.Contains(item);
   }

   public void CopyTo(T[] array, int arrayIndex)
   {
       _items.CopyTo(array, arrayIndex);
   }

   public int Count
   {
       get { return _items.Count; }
   }

   public bool IsReadOnly
   {
       get { return false; }
   }

   public bool Remove(T item)
   {
       return _items.Remove(item);
   }

   public IEnumerator<T> GetEnumerator()
   {
       return _items.GetEnumerator();
   }

   System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
   {
       return _items.GetEnumerator();
   }
}

and now use

public class SomeClass
{
   public SimpleCollection<double> ListOfDoubles { get; set; };
   public SimpleCollection<int> ListOfIntegers { get; set; }
}

you can see this page

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