[英]"There is no boxing conversion" error with generic type in Microsoft.Data.Analysis package
[英]Boxing error with generic function
如果我注釋掉我的靜態類,則可以正常編譯。 但是我想讓靜態類工作,所以我可以在main中使用第一個注釋掉的行。 我的錯誤是
錯誤CS0314:類型'T'不能用作通用類型或方法'DateTest.Range'中的類型參數'T'。 沒有從“ T”到“ System.IComparable”的裝箱轉換或類型參數轉換。
我的來源是
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DateTest
{
class Program
{
static void Main(string[] args)
{
//Range.Create(new DateTime(2013, 1, 1), new DateTime(2015, 1, 1), s => s.AddYears(1));
new Range<DateTime>(new DateTime(2013, 1, 1), new DateTime(2015, 1, 1), s => s.AddYears(1));
}
}
static class Range { public static Range<T> Create<T>(T s, T e, Func<T,T> inc) { return new Range<T>(s, e, inc); } }
class Range<T> : IEnumerator<T> where T : IComparable
{
T start, pos, end;
Func<T,T> inc;
public Range(T s, T e, Func<T,T> inc) { pos=start= s; end = e; this.inc = inc; }
public T Current
{
get { return pos; }
}
public void Dispose()
{
throw new NotImplementedException();
}
object System.Collections.IEnumerator.Current
{
get { return pos; }
}
public bool MoveNext()
{
pos = inc(pos);
return pos.CompareTo(end) != 0;
}
public void Reset()
{
pos = start;
}
}
}
您的靜態Create
方法必須具有Range<T>
類應用於其通用參數的所有約束:
static class Range
{
public static Range<T> Create<T>(T s, T e, Func<T, T> inc)
where T : IComparable //this line was added
{
return new Range<T>(s, e, inc);
}
}
就這樣。
由於Range
類要求T
具有可比性,因此Create
方法需要確保自己的T
也具有可比性。
附帶說明一下,您可以考慮使用IComparable<T>
作為兩者的約束,而不是IComparable
,以確保比較的靜態類型。
約定還將聲明Range
實現IEnumerable<T>
而不是IEnumerator<T>
以便可以同時由多個源迭代相同的范圍,並且還允許您在foreach
循環和許多其他庫方法中使用該類型。 (即LINQ的全部)基於IEnumerable<T>
接口構建的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.