2017-05-31 107 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.