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'
我怎麼解決這個問題?
'T'可以是任何類型。如果它是一個Person對象,如何將它們添加到一起?簡單的答案是,似乎沒有任何簡單的方法可以將'T'限制爲數字類型。請參閱:http://stackoverflow.com/questions/32664/c-sharp-generic-constraint-for-only-integers –
我不認爲你可以。它需要對T進行約束,要求它有一個加號運算符,並且據我所知這是不可能的。 – Alxandr
你可以查看這個鏈接:http://stackoverflow.com/questions/1251507/is-it-possible-to-call-value-type-operators-via-reflection –