【发布时间】:2016-11-09 11:12:53
【问题描述】:
我有这样的课:
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 但它有错误
无法将 null 转换为类型参数“T”,因为它可能是 不可为空的值类型。考虑改用“default(T)”。
我希望返回值是 null 而不是 default(T)。
我该怎么办?
【问题讨论】:
-
查看SO answer。
-
如果您希望它能够返回
null,那么您需要将其设为可为空的类型,或者对T 施加约束以使用T : class使其成为引用类型。 -
你的情况是什么?
-
你认为
default(T)是什么?对于引用类型,其计算结果为null。对于值类型(例如int),这要么为零,要么为默认类型的任何类型。