简体   繁体   English

C#打开通用类型比较。 通用&lt;&gt;是通用的“父级” <T> ?

[英]C# Open generic type comparison. Generic<> is “parent” of Generic<T>?

I have a class MyGeneric<T>, and some cached data created from type MyGeneric<string>, MyGeneric<int>, MyGeneric<double>... etc. 我有一个类MyGeneric <T>,以及一些从类型MyGeneric <string>,MyGeneric <int>,MyGeneric <double> ...等创建的缓存数据。

Somewhere I have to check certain data to see if it is MyGeneric, I code like this: 我必须在某些地方检查某些数据以查看它是否是MyGeneric,我这样编码:

if (data is MyGeneric<>) { // can't compile
    // ... do something
}

or 要么

if (data.GetType() == typeof(MyGeneric<>)
    || typeof(MyGeneric<>).isAssginableFrom(data.GetType())) { 
    // no exception but none of these comparison works
}

or this kind of stupid implemention works but i'd like to throw it away: 或这种愚蠢的实现工作,但我想扔掉它:

if (data.GetType().Name.StartsWith(typeof(MyGeneric<>).Name) { ... }

Is there a way to check relations between actual data type and open generic type (MyGeneric<>) ? 有没有一种方法可以检查实际数据类型和开放通用类型(MyGeneric <>)之间的关系?

What you call open generic type is known as generic type definition : 您所谓的开放通用类型称为通用类型定义

if(data.GetType().GetGenericTypeDefinition() == typeof(MyGeneric<>))
{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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