【问题标题】:Cant evaluate types of IList when looping properties循环属性时无法评估列表的类型
【发布时间】:2011-06-30 03:54:06
【问题描述】:

我有一个带有属性的类。我们将调用此 TestMeCommand(见下文)。这个类有一个列表。我需要做的是遍历类的属性,并识别列表。现在必须通用地构建它,因为它的代码用于验证,所以同样的代码可能需要识别 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 is IList 之类的事情,它永远不会评估为真。我该如何解决?

【问题讨论】:

    标签: c# reflection properties


    【解决方案1】:

    我可能会使用:

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

    其中涵盖了实现IList 的任何内容。

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

    【讨论】:

    • 哇,当橙色条出现时,哇!可惜我没票了。
    • 你是大师。我知道它是这样的,但除非你说得这么简单,否则我无法理解它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 2017-01-28
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多