简体   繁体   中英

How to check if type is IEnumerable<BaseType>?

Should be easy...

class Base{}    
class Foo:Base{}

public bool Bar(Type t){
  // return ???
  // NB: shouldn't know anything about Foo, just Base
}

Assert.True(Bar(typeof(IEnumerable<Foo>));
Assert.False(Bar(typeof(IEnumerable<Base>));
Assert.False(Bar(typeof(string));
Assert.False(Bar(typeof(Foo));

Just to answer question why 2nd one should be false (actually - it does not matter, cause Bar argument will never be IEnumerable<Base> ).

I'm trying to write FluentNhibernate auto mapping convention which maps my class enumerations to integers. I successfully did that already, but things went down when I wanted to map IEnumerable<EnumerationChild> (in my case - User.Roles).

public class EnumerationConvention:IUserTypeConvention{
    private static readonly Type OpenType=typeof(EnumerationType<>);
    public void Apply(IPropertyInstance instance){
      //this is borked atm, must implement ienumerable case
      var closedType=OpenType.MakeGenericType(instance.Property.PropertyType);
      instance.CustomType(closedType);
    }
    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria){
      criteria.Expect(
        x=>typeof(Enumeration).IsAssignableFrom(x.Property.PropertyType) ||  
           typeof(IEnumerable<Enumeration>)
             .IsAssignableFrom(x.Property.PropertyType));
    }
  }

You can use Type.IsAssignableFrom(Type) . However, your question isn't really clear - you're specifying one type, but you need two... which type is Bar meant to be checking t against?

Note that the answer will change between .NET 3.5 and .NET 4, due to generic covariance - in .NET 3.5, for example, a List<Foo> is not assignable to IEnumerable<Base> , but in .NET 4 it is.

EDIT: Here's a program which prints True, True, False, False. I'm not sure why you expected the second one to be false:

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

class Base{}    
class Foo:Base{}

class Test
{
    static bool Bar(Type t)
    {
        return typeof(IEnumerable<Base>).IsAssignableFrom(t);
    }

    static void Main()
    {
        Console.WriteLine(Bar(typeof(IEnumerable<Foo>)));
        Console.WriteLine(Bar(typeof(IEnumerable<Base>)));
        Console.WriteLine(Bar(typeof(string)));
        Console.WriteLine(Bar(typeof(Foo)));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM