繁体   English   中英

在.NET 2.0中将对象转换为IEnumerable

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM