2017-05-31 45 views
0

我可以更改HashSet的原型吗?我想达到的目的是在创建HashSet时添加一个属性count,该属性将在每个.Add().Remove()操作期间更新。我认为它会比迭代更好。我想这样做也为SortedHash和Dictionary和SortedDictionary(你明白了)。更改HashSet原型C#

编辑:通过原型我的意思是像在JavaScript中,我可以说,例如Array.prototype。我希望它与C#一样。

+12

所有这些类已经一个'Count'财产 –

+0

这听起来像[XY问题](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。您正在询问有关尝试或假定的解决方案,而不是实际问题。什么是*实际*问题,为什么你认为你需要改变一个原型来修复它? –

回答

6

不,您不能在C#中更改原型,因为C#不是原型语言。不过,HashSet<T>已经有 a .Count财产。如果你愿意,你可以使用扩展方法来添加额外的方法。扩展属性可能出现在不太远的语言更新中。或者:子类并在子类中添加属性。

2

您不必因为所有那些收藏已经有一个Count属性,它正是你想要的。

关于“改变原型”:不。在C#中没有这样的东西。最接近的将是一个扩展方法。

比方说,你将要添加到HashSet的方法,该方法返回计数:

static class HashSetExtensions // needs to be static 
{ 
    public static int GetCount(this HashSet set) // notice the 'this' which indicates an extension method 
    { 
     int count = set.Count; // you can access the public interface of the type in your extension method 
     return count; 
    } 
} 

而且用法是:

var myHashSet = new HashSet<int>(); 
var count = myHashSet.GetCount(); // GetCount is the extension method and you call it just like you call a normal method.