为什么我不能使用Guid作为泛型类型约束?

Gez*_*zim 2 c# generics types constraints

我有如下通用方法,我想将T限制为仅像Guid这样的类型:

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

编译器告诉我

'System.Guid'不是有效的约束.用作约束的类型必须是接口,非密封类或类型参数.

那么,为什么这不起作用?

Gez*_*zim 6

首先,事实证明这Guid是一个struct.您不能为a设置泛型约束,struct因为struct无法从中派生(意味着您不能从a继承struct).

除此之外,where T: Guid真正读取"其中T是类型Guid或类型来源于Guid",并且由于没有任何东西可以从a得到struct,它就像是说"哪里的T是Guid类型",它打破了泛型的目的.