循环属性时无法评估 IList 的类型
我有一个带有属性的类。我们将此称为 TestMeCommand(见下文)。这个类有一个列表。我需要做的是循环类的属性,并识别列表。现在必须通用地构建它,因为它的代码用于验证,因此相同的代码可能需要标识 List
或 List
或其他内容。
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 这样的操作,它永远不会计算为 true。我该如何修复它?
I have a class with properties on it. We will call this TestMeCommand (see below). This class has a list on it. What I need to do is loop over the properties of the class, and identify the List. Now this has to be built generically because its code for validation, so this same code might need to identify a List<int>
or a List<string>
, or something else.
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; }
}
}
Now the problem is that I have code that looks like this:
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;
}
}
I dont want to put that string in there, but if I do something like prop.PropertyType is IList it never evaluates true. How do I fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我可能会使用:
它涵盖了实现
IList
的任何内容。prop.PropertyType is IList
从未评估为 true 的原因是,这是询问“我的Type
对象是否实现IList
?”,而不是“此Type
对象所表示的类型是否实现了IList
?”。I might use:
which covers anything implementing
IList
.The reason that
prop.PropertyType is IList
never evaluates true is that this is asking "does myType
object implementIList
?", rather than "does the type represented by thisType
object implementIList
?".