非可空类型的一般约束 [英] Generic Constraint for Non Nullable types

查看:84
本文介绍了非可空类型的一般约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

public class KeyDTO<T>
{
     public T Id { get; set; }
}

到目前为止,还不错,但是我希望类型参数 T 是不可为空的类型. 我在某处读到这可能是可行的:

So far so good, but I want the type parameter T to be a non-nullable type. I've read somewhere that this may be feasible:

public class KeyDTO<T> where T : IComparable, IComparable<T>
{
     public T Id { get; set; }
}

但是,如果我将public T Id更改为public T? Id,则会收到编译错误,告诉我T必须不可为空.

But, If i change public T Id to public T? Id, I get a compilation error telling me that T must be non-nullable.

如何指定泛型类型参数必须为非空值?

How can I specify that a generic type parameter must be non-nullable?

我要完成此操作是因为我想用[Required]属性注释我的Id属性,如下所示:

I want to accomplish this because I want to annotate my Id property with the [Required] attribute as follows:

public class KeyDTO<T> {
    [Required]
    public T Id { get; set; }
}

[Required]所做的是验证模型,因此T不能为空.

What [Required] does is validate the model so T cannot be null.

但是,如果我有KeyDTO<int>,则Id将被初始化为0,绕过我的[Required]属性

However, if I have KeyDTO<int>, Id will be initialized to 0, bypassing my [Required] attribute

推荐答案

应用where T : struct会应用通用约束,即T是不可为空的值类型.由于没有不可空的引用类型,因此它具有与所有不可空的类型"完全相同的语义.可空值类型(即Nullable<T>)不满足struct通用约束.

Applying where T : struct applies a generic constraint that T be a non-nullable value type. Since there are no non-nullable reference types, this has the exact same semantics as simply "all non-nullable types". Nullable value types (i.e. Nullable<T>) do not satisfy the struct generic constraint.

这篇关于非可空类型的一般约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆