1、通过IsAssignableFrom()方法判断的问题
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
var type1 = typeof(List<>);
var type2 = typeof(IEnumerable<>);
//return false
Console.WriteLine(type2.IsAssignableFrom(type1));
//通过IsAssignableFrom
//()方法判断,方法返回是false,
//判断不出来它们之间的继承关系。
}
}
}
2、通过自定义方法判断它们之间的继承关系
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication
{
class Program
{
public static bool IsAssignableToOpenGenericType(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 IsAssignableToOpenGenericType(baseType, genericType);
}
static void Main(string[] args)
{
//IsAssignableToOpenGenericType()使用示例代码
var typ1 = typeof(List<>);
var typ2 = typeof(IEnumerable<>);
//true, List<>的类型定义包含一个IEnumerable<>
Console.WriteLine(IsAssignableToOpenGenericType(typ1,typ2));
//false,IEnumerable<>的类型定义不包含List<>
Console.WriteLine(IsAssignableToOpenGenericType(typ2,typ1));
}
}
}