繁体   English   中英

如何检查类型是否为IEnumerable <BaseType> ?

[英]How to check if type is IEnumerable<BaseType>?

应该很容易...

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

只是为了回答第二个为什么应该为假的问题(实际上-没关系,因为Bar参数永远不会是IEnumerable<Base> )。

我正在尝试编写FluentNhibernate自动映射约定,该约定将我的类枚举映射到整数。 我已经成功地做到了,但是当我想映射IEnumerable<EnumerationChild> (我的情况是-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));
    }
  }

您可以使用Type.IsAssignableFrom(Type) 但是,您的问题还不是很清楚-您要指定一种类型,但需要两种类型…… Bar是要检查t哪种类型?

请注意,由于通用协方差,答案将在.NET 3.5和.NET 4之间发生变化-例如,在.NET 3.5中, 不能List<Foo>分配给IEnumerable<Base> ,但是在.NET 4中可以。

编辑:这是一个打印True,True,False,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)));
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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