[英]Convert object to IEnumerable in .NET 2.0
我在写通用验证函数。 它将使用反射来浏览对象的属性并对其进行验证。 但是我对收藏财产有疑问。 我可以确定它是array
还是generic
但是无法强制转换以遍历其实体。
private static bool Validate(object model)
{
if (model.GetType().IsGenericType || model.GetType().IsArray)
{
//I want to convert model to IEnumerable here in order to loop throught it
//It seems that .NET 2.0 doesn't allow me to cast by using
IEnumerable lst = model as IEnumerable;
//or
IEnumerable lst = (IEnumerable) model;
}
}
更新:
愚蠢的我,原来是
IEnumerable lst = model as IEnumerable;
完美地工作。 我遇到的问题是,从.NET 4.0切换到.NET 2.0,我得出的结论是:.NET 2.0在不提供特定类型的情况下不支持直接强制转换为IEnumerable
,而且我还没有注意到System.Collection
尚未导入。 我现在感觉像个白痴。
P / S:对不起,你们浪费时间
IEnumerable lst = model as IEnumerable;
if(lst != null)
{
//loop
}
如果模型实现IEnumerable
则此方法应该起作用。
以下内容将引发无效的强制转换异常:
IEnumerable lst = (IEnumerable) model;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.