且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何找出如果一个对象的类型实现IEnumerable< X>其中X从基地使用反射派生

更新时间:2023-11-23 17:11:04

您也可以使用的 LINQ 查询可能看起来像这样。

You could also use a LINQ query that could look like this.

public static bool ImplementsBaseType(IEnumerable objects)
{
    int found = ( from i in objects.GetType().GetInterfaces()
                 where i.IsGenericType && 
                       i.GetGenericTypeDefinition() == typeof(IEnumerable<>) &&
                       typeof(MyBaseClass).IsAssignableFrom(i.GetGenericArguments()[0])
                 select i ).Count();

    return (found > 0);
}

这代码假定以下using语句:

This code assumes the following using statements:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;



由于这只是一个思想实验。这里是另一个实现作为一个扩展方法。

Since this is just a thought experiment. Here is another implementation as an extension method.

public static class ConversionAssistants
{
    public static bool GenericImplementsType(this IEnumerable objects, Type baseType)
    {
        foreach (Type type in objects.GetType().GetInterfaces())
        {
            if (type.IsGenericType)
            {
                if (type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
                {
                    if (baseType.IsAssignableFrom(type.GetGenericArguments()[0]))
                        return true;
                }
            }
        }
        return false;
    }
}