通用 class 的空值
Null value for generic class
我有一个 class 这样的:
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];
}
}
}
}
我正在创建一个从列表派生的 class 并创建一个 属性 来获取当前项目。
如果 SelectedIndex
是一个错误的值,我正在 returning null
但它有一个错误
Cannot convert null to type parameter 'T' because it could be a
non-nullable value type. Consider using 'default(T)' instead.
我希望 return 值为 null
而不是 default(T)
。
我该怎么办?
null
是 int
或 double
等值类型的无效值。因此,您必须将泛型类型参数限制为 类,如下所示:
public class MyList<T> : List<T> where T : class
然后,编译错误就会消失。
我有一个 class 这样的:
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];
}
}
}
}
我正在创建一个从列表派生的 class 并创建一个 属性 来获取当前项目。
如果 SelectedIndex
是一个错误的值,我正在 returning null
但它有一个错误
Cannot convert null to type parameter 'T' because it could be a non-nullable value type. Consider using 'default(T)' instead.
我希望 return 值为 null
而不是 default(T)
。
我该怎么办?
null
是 int
或 double
等值类型的无效值。因此,您必须将泛型类型参数限制为 类,如下所示:
public class MyList<T> : List<T> where T : class
然后,编译错误就会消失。