class SetMap : KeyedCollection<Type, object>
{
public HashSet<T> Use<T>(IEnumerable<T> sourceData)
{
var set = new HashSet<T>(sourceData);
if (Contains(typeof(T)))
{
Remove(typeof(T));
}
Add(set);
return set;
}
public HashSet<T> Get <T>()
{
return (HashSet<T>) this[typeof(T)];
}
protected override Type GetKeyForItem(object item)
{
return item.GetType().GetGenericArguments().Single();
}
}
would anyone clarify this for me pls. return (HashSet) this[typeof(T)]; with example if possible. thank you
return (HashSet) this[typeof(T)];
Let me split the statement into parts.
(1) this[...]
means using the indexer of this
. And this
basically means "this object".
(2) The indexer accepts a Type
. And in this call to the indexer, the argument is typeof(T)
.
(3) typeof
gets a Type
object that corresponds to the type in the ()
. In this case, the generic type parameter T
. And the indexer returns an object
.
The parameter (Type
) and return type (object
) of the indexer can be inferred from the base type of the class: KeyedCollection<Type, object>
. I think you can understand this.
(4) The value returned by the indexer gets casted into a HashSet<T>
. Again, T
is the generic type argument.
(5) The value gets returned to the caller by the return
statement.
For more information:
Indexers: https://msdn.microsoft.com/en-us/library/6x16t2tx.aspx
Generics: https://msdn.microsoft.com/en-us/library/512aeb7t.aspx
Casting: https://msdn.microsoft.com/en-us/library/ms173105.aspx\
KeyedCollection
: https://msdn.microsoft.com/en-us/library/ms132438(v=vs.110).aspx
typeof
: https://msdn.microsoft.com/en-us/library/58918ffs.aspx