我知道有很多問題上讓喜歡本
"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