Cra*_*art 1 c# reflection properties
我有一个属性的类.我们将调用此TestMeCommand(见下文).这个类有一个列表.我需要做的是遍历类的属性,并识别List.现在必须一般地构建它,因为它的验证代码,所以这个相同的代码可能需要识别a List<int>或a 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; }
}
}
Run Code Online (Sandbox Code Playgroud)
现在问题是我的代码看起来像这样:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我不想把那个字符串放在那里,但如果我做prop.PropertyType之类的东西是IList它永远不会评估为true.我如何解决它?
我可能会用:
if(typeof(IList).IsAssignableFrom(prop.PropertyType)) {...}
Run Code Online (Sandbox Code Playgroud)
涵盖任何实施IList.
prop.PropertyType is IList永远不会评估为true 的原因是,这是在问"我的Type对象是否实现IList?",而不是" 该对象所代表的类型是否Type实现IList?".