简体   繁体   中英

Generic Constraint for Non Nullable types

I have the following class:

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

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; }
}

But, If i change public T Id to public T? Id 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?

Edit

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; }
}

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

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

从 C# 8.0 开始,您现在可以使用where T : notnull泛型约束来指定T是不可为空的类型。

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 (ie Nullable<T> ) do not satisfy the struct generic constraint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM