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 =*=*=*=*=*=*=*=*=*=");
}
}
}
}
}
你好〜
我想运行此代码,但我收到了错误消息
error CS0019: Operator '+' cannot be applied to operands of type 'T' and 'T'
如何解决此错误?
答案 0 :(得分: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);
答案 1 :(得分:0)
如果您确定T
始终是int,请将T
强制转换为int。
baskets[pivot] = ((int)baskets[previousPivot]) + (int)plusValue;
但是,如果T
总是一个int,那么将它设为泛型并没有多大意义。
答案 2 :(得分:-1)
通用运算符有library。