循环属性时无法评估List的类型

时间:2011-02-18 22:47:50

标签: c# reflection properties

我有一个包含属性的类。我们将调用此TestMeCommand(见下文)。这个类有一个列表。我需要做的是遍历类的属性,并识别List。现在必须一般地构建它,因为它的验证代码,因此相同的代码可能需要识别List<int>List<string>或其他内容。

public class TestMeCommand
{
    [Range(1, Int32.MaxValue)]
    public int TheInt { get; set; }

    [Required]
    [StringLength(50)]
    public string TheString { get; set; }

    [ListNotEmptyValidator]
    public List<TestListItem> MyList { get; set; }

    public class TestListItem
    {
        [Range(1, Int32.MaxValue)]
        public int ListInt { get; set; }
    }
}

现在问题是我的代码看起来像这样:

foreach (var prop in this.GetType().GetProperties())
{
    if (prop.PropertyType.FullName.StartsWith("System.Collections.Generic.List"))
    {
        IList list = prop.GetGetMethod().Invoke(this, null) as IList;
    }
}

我不想把那个字符串放在那里,但如果我做prop.PropertyType之类的东西是IList,它永远不会评估为true。我该如何解决?

1 个答案:

答案 0 :(得分:5)

我可以使用:

if(typeof(IList).IsAssignableFrom(prop.PropertyType)) {...}

涵盖了实施IList的任何内容。

prop.PropertyType is IList永远不会评估为true的原因是,这是在问“我的Type对象是否实现IList?”,而不是“类型代表通过此Type对象工具IList?“。

相关问题