使用IsAssignableFrom泛型

编程入门 行业动态 更新时间:2024-10-26 18:25:44
本文介绍了使用IsAssignableFrom泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用反射,我试图找到一套从给定的基类继承的类型。它没有多久找出简单的类型,但我难倒当谈到仿制药。

Using reflection, I'm attempting to find the set of types which inherit from a given base class. It didn't take long to figure out for simple types, but I'm stumped when it comes to generics.

有关这块code,第一IsAssignableFrom返回true,但第二个返回false。然而,最终的分配编译就好了。

For this piece of code, the first IsAssignableFrom returns true, but the second returns false. And yet, the final assignment compiles just fine.

class class1 { } class class2 : class1 { } class generic1<T> { } class generic2<T> : generic1<T> { } class Program { static void Main(string[] args) { Type c1 = typeof(class1); Type c2 = typeof(class2); Console.WriteLine("c1.IsAssignableFrom(c2): {0}", c1.IsAssignableFrom(c2)); Type g1 = typeof(generic1<>); Type g2 = typeof(generic2<>); Console.WriteLine("g1.IsAssignableFrom(g2): {0}", g1.IsAssignableFrom(g2)); generic1<class1> cc = new generic2<class1>(); } }

那么,如何在运行时确定一个通用的类型定义是否从另一个派生?

So how do I determine at run time whether one generic type definition is derived from another?

推荐答案

从回答另一个问题:

public static bool IsAssignableToGenericType(Type givenType, Type genericType) { var interfaceTypes = givenType.GetInterfaces(); foreach (var it in interfaceTypes) { if (it.IsGenericType && it.GetGenericTypeDefinition() == genericType) return true; } if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType) return true; Type baseType = givenType.BaseType; if (baseType == null) return false; return IsAssignableToGenericType(baseType, genericType); }

(如果你喜欢的答案,请给予好评链接的答案,因为code是不是我的。)

(If you like the answer please upvote the linked answer since the code isn’t mine.)

更多推荐

使用IsAssignableFrom泛型

本文发布于:2023-11-16 17:27:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1606352.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:IsAssignableFrom   泛型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!