EZL*_*ner 11 .net c# generics types
说我有以下课程:
public class General<T> { }
Run Code Online (Sandbox Code Playgroud)
我想知道一个对象是否属于那种类型.我知道我可以使用反射来找出该对象是否属于该泛型类型Type.GetGenericTypeDefinition,但我想避免这种情况.
是否有可能做某事obj is General<T>,或obj.GetType().IsAssignableFrom(typeof(General<T>))?
我很惊讶我找不到类似的问题,尽管我在搜索中可能使用了错误的关键字.
你可以这样做:
var obj = new General<int>();
var type = obj.GetType();
var isGeneral =
(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(General<>)) ||
type.GetBaseTypes().Any(x => x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(General<>));
Run Code Online (Sandbox Code Playgroud)
GetBaseTypes以下扩展方法在哪里:
public static IEnumerable<Type> GetBaseTypes(this Type type)
{
if (type.BaseType == null) return type.GetInterfaces();
return new []{type}.Concat(
Enumerable.Repeat(type.BaseType, 1)
.Concat(type.GetInterfaces())
.Concat(type.GetInterfaces().SelectMany<Type, Type>(GetBaseTypes))
.Concat(type.BaseType.GetBaseTypes()));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4573 次 |
| 最近记录: |