I have a DICOM dictionary that contains a set of objects all deriving from DataElement. The dictionary has an int as a key, and the DataElement as property. My DICOM dictionary contains a this[] property where I can access the DataElement, like this:
public class DicomDictionary
{
Dictionary<int, DataElement> myElements = new Dictionary<int, DataElement>();
.
.
public DataElement this[int DataElementTag]
{
get
{
return myElements[int];
}
}
}
A problem now is that I have different DataElement types all deriving from DataElement, like DataElementSQ, DataElementOB and so on. What I wanted to do now is the following to make writing in C# a little bit easier:
public T this<T>[int DataElementTag] where T : DataElement
{
get
{
return myElements[int];
}
}
But this is not really possible. Is there something I have missed? Of course I could do it with Getter method, but it开发者_Python百科 would be much nicer to have it this way.
The best options are to either use a generic method (instead of an indexer), or to have your class be generic (in which case, the indexer would be tied to the class generic type). A generic indexer as you've described is not allowed in C#.
Why not use a real generic method GetDataElement<T> where T : DataElement
instead? Generic indexers are not supported in C#. Why do you think in this case an indexer is better than a method?
Is it a case for you?
public class DicomDictionary<TElement>
{
Dictionary<int, TElement> myElements = new Dictionary<int, TElement>();
public TElement this[int DataElementTag]
{
get
{
return myElements[int];
}
}
}
Append for sll answer is:
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 without change the 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 method to parse for the generic type:
public T Get<T>(string key)
where T : class
{
return (T)Convert.ChangeType(acessor[key], typeof(T));
}
精彩评论