Can I get the general property []?

I have a DICOM dictionary containing a collection of objects, all of which are derived from a DataElement. The dictionary has an int as a key and a DataElement as property. My DICOM dictionary has this property [], where I can access the DataElement, for example:

public class DicomDictionary { Dictionary<int, DataElement> myElements = new Dictionary<int, DataElement>(); . . public DataElement this[int DataElementTag] { get { return myElements[int]; } } } 

Now the problem is that I have different types of DataElement, all of which are based on DataElement, like DataElementSQ, DataElementOB, etc. Now, I would like to do the following to make writing in C # a little easier:

  public T this<T>[int DataElementTag] where T : DataElement { get { return myElements[int]; } } 

But it is really impossible. Is there something I missed? Of course, I could do this with the Getter method, but it would be much better to have it this way.

+7
source share
4 answers

Why not use the real generic GetDataElement<T> where T : DataElement instead? Generic indexes are not supported in C #. Why, in your opinion, is the index better than the method in this case?

+3
source

The best options are either to use a common method (instead of an indexer) or to have a common class (in this case, the indexer will be bound to the generic type class). The generic index, as you described, is not allowed in C #.

+4
source

Is this a business for you?

 public class DicomDictionary<TElement> { Dictionary<int, TElement> myElements = new Dictionary<int, TElement>(); public TElement this[int DataElementTag] { get { return myElements[int]; } } } 
+2
source

Attach for sll response:

 public class Acessor<TKey, TValue> where TKey : IComparable where TValue : class { Dictionary<TKey, TValue> myElements = new Dictionary<TKey, TValue>(); public TValue this[TKey key] { get { return myElements[key]; } set { myElements.Add(key, value); } } } 

Or unchanged class signature:

  public class Acessor { Dictionary<string, object> myElements = new Dictionary<string, object>(); public object this[string key] { get { return myElements[key]; } set { myElements.Add(key, value); } } } 

And create a parsing method for the generic type:

 public T Get<T>(string key) where T : class { return (T)Convert.ChangeType(acessor[key], typeof(T)); } 
0
source

All Articles