本文介绍了如何找出如果一个对象的类型实现IEnumerable< X>其中X从基地使用反射派生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给一个基类基本,我想写的方法测试,如:

Give a base class Base, I want to write a method Test, like this:

private static bool Test(IEnumerable enumerable)
{
...
}

这样的测试如果o的类型实现的IEnumerable中任何界面返回true; X> ,其中 X 从派生基地,这样,如果我这样做:

such that Test returns true if the type of o implements any interface of IEnumerable<X> where X derives from Base, so that if I would do this:

public static IEnumerable<string> Convert(IEnumerable enumerable)
{
    if (Test(enumerable))
    {
        return enumerable.Cast<Base>().Select(b => b.SomePropertyThatIsString);
    }

    return enumerable.Cast<object>().Select(o => o.ToString());
}



...它会做正确的事,使用反射。我敢肯定,它的整个类型的所有接口行走的问题,找到第一个相匹配的要求,但我有一个很难找到普通的的IEnumerable<> 其中

当然,我可以这样考虑:

Of course, I could consider this:

public static IEnumerable<string> Convert(IEnumerable enumerable)
{
    return enumerable.Cast<object>().Select(o => o is Base ? ((Base)o).SomePropertyThatIsString : o.ToString());
}



...但认为它是一个思想实验。

...but think of it as a thought experiment.

推荐答案

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

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;
    }
}

这篇关于如何找出如果一个对象的类型实现IEnumerable&LT; X&GT;其中X从基地使用反射派生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 01:27