反射泛型类型的 "is" 运算符的等价物是什么?
What is the equivalent of the "is" operator for reflected generic types?
在 C# 中对泛型类型使用 is
运算符非常简单:
if (new List<MyClass>()) is IEnumerable<MyClass>) {
// always branches
}
但是比较类型时呢?我希望我可以在这里使用 Type.IsSubclassOf(Type type)
,但是 System.Collections.Generic.List<>
implements System.Collections.Generic.IEnumerable<>
-- 它不会 extend 它。所以我认为这就是为什么会发生以下情况:
var listType = typeof(List<MyClass>);
var enumerableType = typeof(IEnumerable<MyClass>);
if (listType.IsSubclassOf(enumerableType)) {
// NEVER branches
}
如果我有一个右值 Type
的实例,我可以轻松地使用 Type.IsInstanceOfType(object o)
,但是代码中的这一点与所讨论的 Type
所在的实例相去甚远被反映了。
我是否在 Type
API 中遗漏了什么?我是否被迫通过扩展方法推出自己的产品?
使用Type.IsAssignableFrom(类型)
在 C# 中对泛型类型使用 is
运算符非常简单:
if (new List<MyClass>()) is IEnumerable<MyClass>) {
// always branches
}
但是比较类型时呢?我希望我可以在这里使用 Type.IsSubclassOf(Type type)
,但是 System.Collections.Generic.List<>
implements System.Collections.Generic.IEnumerable<>
-- 它不会 extend 它。所以我认为这就是为什么会发生以下情况:
var listType = typeof(List<MyClass>);
var enumerableType = typeof(IEnumerable<MyClass>);
if (listType.IsSubclassOf(enumerableType)) {
// NEVER branches
}
如果我有一个右值 Type
的实例,我可以轻松地使用 Type.IsInstanceOfType(object o)
,但是代码中的这一点与所讨论的 Type
所在的实例相去甚远被反映了。
我是否在 Type
API 中遗漏了什么?我是否被迫通过扩展方法推出自己的产品?
使用Type.IsAssignableFrom(类型)