我有一堂这样的课:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
public class MyList<T> : List<T>
{
public int SelectedIndex { get; set; }
public T CurrentItem
{
get
{
if (this.SelectedIndex > this.Count)
return null;
return this[this.SelectedIndex];
}
}
}
}
我正在创建一个从列表派生的类,并创建一个用于获取当前项目的属性。
如果SelectedIndex
是一个错误的值,我返回 null
但有一个错误
Cannot convert null to type parameter 'T' because it could be a non-nullable value type. Consider using 'default(T)' instead.
我希望返回值为null
不是default(T)
.
我该怎么办?
最佳答案
null
对于 int
或 double
等值类型来说是无效值。因此,您必须将泛型类型参数限制为类,如下所示:
public class MyList<T> : List<T> where T : class
然后,编译器错误就会消失。
关于c# - 泛型类的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40505604/