我知道有很多问题上让喜欢本
"Operator 'whatever' cannot be applied to operands of type 'T'
(无论可++,+ =或< =等等等等,但忍耐一下,我想问问不同的东西。在C#5.0中改进了泛型类型的特性/运算符重载吗?
比方说,我有这个代码
public class GenericCls<T> where T : struct
{
public static T AddValues(params T[] values)
{
T sum = default(T);
if (values != null)
{
for (int i = 0; i < values.Length; i++)
{
sum += values[i];
}
}
return sum;
}
}
即使我做了我喜欢的类型结构,和值类型我得到的错误 Operator '+=' cannot be applied to operands of type 'T' and 'T'
如果我尽量隐蔽,并应用值类型约束,它说: Constraint cannot be special class 'System.ValueType'
如果我试图把在for循环为T类型的参数,这样做..
public class GenericCls<T> where T : struct, IComparable<T>, IEquatable<T>
{
public static T AddValues(params T[] values)
{
T sum = default(T);
if (values != null)
{
for (T i = default(T); i < values.Length; i++)
{
sum += values[i];
}
}
return sum;
}
}
我仍然得到错误
Operator '<' cannot be applied to operands of type 'T' and 'int'
Operator '++' cannot be applied to operand of type 'T'
Cannot implicitly convert type 'T' to 'int'
无论如何,我无法让它工作。我正在使用VS2010(C#4.0,.NET 4.0)。所以我想知道什么时候C#5.0将最终与VS2012一起发布(据我所知,他们仍然处于测试阶段吧?)它会照顾这些问题吗?还是我们再次对泛型使用有太多限制?
不 - 你能做的最好的是传递'Func键'你的方法,你要执行的操作。然后你可以使用'values.Aggregate(default(T),operatorFunc)'。 –
Lee
2012-07-28 13:14:51
下面的详细信息*一些突破性的变化5,有些可能适用于您的问题:http://msdn.microsoft.com/en-us/library/hh678682(v=vs.110).aspx – 2012-07-28 14:44:37