c# - 泛型类的空值

标签 c# .net generics

我有一堂这样的课:

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 对于 intdouble 等值类型来说是无效值。因此,您必须将泛型类型参数限制为类,如下所示:

public class MyList<T> : List<T> where T : class

然后,编译器错误就会消失。

关于c# - 泛型类的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40505604/

相关文章:

c# - 在非异步方法中返回异步任务的正确方法

Java在泛型方法中使用泛型数组

java - 强制转换设置为可迭代

java - 泛型类型 : not applicable for the arguments

c# - ASP.NET-如何定期监控数据库表?

c# - System.Collections.Generic.Dictionary<T,T>.Equals 实际上做了什么?

.net - 通用ILogger,或者通过Serilog,添加logging属性

.net - 启用/禁用 Azure 流量管理器端点

c# - 使用 FIFO 进行过滤

c# - 我可以在 C# 中获得 XML 的具体示例吗