【问题标题】:Null value for generic class [duplicate]泛型类的空值 [重复]
【发布时间】: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),这要么为零,要么为默认类型的任何类型。

标签: c# .net generics


【解决方案1】:

nullintdouble 等值类型的无效值。因此,您必须将泛型类型参数限制为如下类:

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

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

【讨论】:

    猜你喜欢
    • 2019-06-04
    • 2011-08-19
    • 2010-09-27
    • 2018-06-12
    • 2021-12-04
    • 2015-11-20
    • 1970-01-01
    • 2013-11-27
    • 2011-04-16
    相关资源
    最近更新 更多