2013-10-30 39 views
1
using System.Collections; 
using System; 

public class Counter<T> 
{ 
    private int pivot = 0; 
    private readonly int arraySize = 256; 
    private bool startCheck = false; 

    T[] baskets; 

    public T Count 
    { 
     get 
     { 
      return baskets[pivot]; 
     } 
    } 

    public void CountPlus(T plusValue) 
    { 
     if(!startCheck) 
     { 
      startCheck = true; 

      baskets[pivot] = plusValue; 
     } 
     else 
     { 
      int previousPivot = pivot; 

      pivot++; 

      if(previousPivot == arraySize - 1) 
      { 
       pivot = 0; 
      } 

      checked 
      { 
       try 
       { 
        baskets[pivot] = baskets[previousPivot] + plusValue; 
       } 
       catch(OverflowException ofe) 
       { 
        Debug.Log("=*=*=*=*=*=*=*=*= OverflowException =*=*=*=*=*=*=*=*=*="); 
       } 
      } 

     } 
    } 
} 

你好〜如何添加T和T

我要運行該代碼,但我有一個錯誤信息

error CS0019: Operator '+' cannot be applied to operands of type 'T' and 'T'

我怎麼解決這個問題?

+0

'T'可以是任何類型。如果它是一個Person對象,如何將它們添加到一起?簡單的答案是,似乎沒有任何簡單的方法可以將'T'限制爲數字類型。請參閱:http://stackoverflow.com/questions/32664/c-sharp-generic-constraint-for-only-integers –

+0

我不認爲你可以。它需要對T進行約束,要求它有一個加號運算符,並且據我所知這是不可能的。 – Alxandr

+0

你可以查看這個鏈接:http://stackoverflow.com/questions/1251507/is-it-possible-to-call-value-type-operators-via-reflection –

回答

1

你可以使用動態:

dynamic o1 = baskets[previousPivot]; 
dynamic o2 = plusValue; 
baskets[pivot] = o1 + o2; 

那麼這樣的代碼工作:

Counter<int> intCounter = new Counter<int>(); 
intCounter.CountPlus(3); 
intCounter.CountPlus(5); 

Counter<double> doubleCounter = new Counter<double>(); 
doubleCounter.CountPlus(2.1); 
doubleCounter.CountPlus(3.8); 
0

如果您確定T始終是一個整數,則將您的T轉換爲int。

baskets[pivot] = ((int)baskets[previousPivot]) + (int)plusValue; 

但是,如果T總是將是一個int,它沒有多大意義,有它的通用。

-1

通用運營商有一個library

相關問題