2009-03-06 100 views

回答

0

您不能重載現有類型的運算符,因爲這可能會破壞使用該類型的任何其他代碼。

您可以創建自己的類來封裝數組,從數組中暴露出您需要的方法和屬性,並重載任何有意義的運算符。

例子:

public class AddableArray<T> : IEnumerable<T> { 

    private T[] _array; 

    public AddableArray(int len) { 
     _array = new T[len]; 
    } 

    public AddableArray(params T[] values) : this((IEnumerable<T>)values) {} 

    public AddableArray(IEnumerable<T> values) { 
     int len; 
     if (values is ICollection<T>) { 
      len = ((ICollection<T>)values).Count; 
     } else { 
      len = values.Count(); 
     } 
     _array = new T[len]; 
     int pos = 0; 
     foreach (T value in values) { 
      _array[pos] = value; 
      pos++; 
     } 
    } 

    public int Length { get { return _array.Length; } } 

    public T this[int index] { 
     get { return _array[index]; } 
     set { _array[index] = value; } 
    } 

    public static AddableArray<T> operator +(AddableArray<T> a1, AddableArray<T> a2) { 
     int len1 = a1.Length; 
     int len2 = a2.Length; 
     AddableArray<T> result = new AddableArray<T>(len1 + len2); 
     for (int i = 0; i < len1; i++) { 
      result[i] = a1[i]; 
     } 
     for (int i = 0; i < len2; i++) { 
      result[len1 + i] = a2[i]; 
     } 
     return result; 
    } 

    public IEnumerator<T> GetEnumerator() { 
     foreach (T value in _array) { 
      yield return value; 
     } 
    } 

    IEnumerator System.Collections.IEnumerable.GetEnumerator() { 
     return _array.GetEnumerator(); 
    } 

} 

用法:

// create two arrays 
AddableArray<int> a1 = new AddableArray<int>(1, 2, 3); 
AddableArray<int> a2 = new AddableArray<int>(4, 5, 6); 

// add them 
AddableArray<int> result = a1 + a2; 

// display the result 
Console.WriteLine(string.Join(", ", result.Select(n=>n.ToString()).ToArray())); 

(注意,因爲這個類實現IEnumerable<T>,你可以在上面使用擴展方法像Select

4

基本上你不能。

您可以使用擴展方法,這樣添加功能:

public void CustomAdd(this Array input, Array addTo) { 
    ... 
} 

但是,這並不與運營商合作。

+0

不宜用運營商在內建類型或擴展方法上重載? – Lennie 2009-03-06 09:26:53

+0

是的 - 即使你能做到這一點,也會導致代碼非常混亂:「爲什麼這個陣列不像他們通常那樣工作?」 – Keith 2009-03-06 10:39:05

1

不能:)

但是,您可以在陣列例如從IEnnumerable或列表繼承......和覆蓋這些運營商。

1

簡短的回答是你不能像@Keith指出的那樣。

較長的答案是,如果要將運算符重載添加到類中,則需要能夠更改該類的源代碼。

在添加操作符來處理兩種不同類型(例如數組+字符串)組合的情況下,您可以更改其中一種類型的源代碼就足夠了。這意味着你應該能夠添加代碼來指定如果你將一個自己的類型添加到數組中,會發生什麼。

在BCL類的情況下,你運氣不好。