【发布时间】: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