简体   繁体   中英

Why can't I use a Guid as a generic type constraint?

I have this generic method as follows and I want to limit T to be only of type Guid like so:

public static EntityFindApiResponse EntityFind<T>(
    Credential cred, EntitiesApiClient entitiesApiClient, string clrType, 
    string propertyName, T searchKey)
    where T: Guid
{
    // ...
}

The compiler tells me that

'System.Guid' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.

So, why isn't this working?

First, it turns out that Guid is a struct . You cannot set a generic constraint to a struct because struct s cannot be derived from (meaning you can't inherit from a struct ).

Further to that where T: Guid really reads "where T is of type Guid or a type that derives from Guid " and since nothing can derived form a struct , it's like saying "where T is of type Guid" which defeats the purpose of generics to begin with.

Guid is a struct, which means it does not meet the requirements:

A type used as a constraint must be an interface, a non-sealed class or a type parameter.

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