需要一些帮助来理解这个方法

Want some help understanding this method

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();
}
}

谁能帮我澄清一下。 return (HashSet) 这个[typeof(T)];如果可能的话,举例说明。 谢谢

它正在使用 generics。一种现代编程概念, 使得设计 classes 和方法成为可能,这些方法和方法将一种或多种类型的规范推迟到 class 或方法由客户端代码声明和实例化。

在您的示例中,它定义了一个可以容纳任何类型的 hashset

阅读我提供的链接中的 MSDN 文档,如果您有更具体的问题post,请点击此处。

return (HashSet) this[typeof(T)];

让我把声明分成几个部分。

(1) this[...]表示使用this的indexer。而 this 基本上意味着 "this object"。

(2) 索引器接受 Type。在这个对索引器的调用中,参数是 typeof(T)

(3) typeof 得到一个 Type 对象对应于 () 中的类型。在这种情况下,泛型类型参数 T。索引器 return 是 object

索引器的参数(Type)和return类型(object)可以从class的基类型推断:KeyedCollection<Type, object>.我想你可以理解这一点。

(4) 由索引器编辑的值 return 被转换为 HashSet<T>。同样,T 是泛型类型参数。

(5) 通过 return 语句将值 return 发送给调用者。

更多信息:

  1. 索引器:https://msdn.microsoft.com/en-us/library/6x16t2tx.aspx

  2. 泛型:https://msdn.microsoft.com/en-us/library/512aeb7t.aspx

  3. 铸造:https://msdn.microsoft.com/en-us/library/ms173105.aspx\

  4. KeyedCollection: https://msdn.microsoft.com/en-us/library/ms132438(v=vs.110).aspx

  5. typeof: https://msdn.microsoft.com/en-us/library/58918ffs.aspx