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

本文关键字:对象 转换 IEnumerable NET | 更新日期: 2023-09-27 18:00:44

我正在编写通用验证函数。它将使用反射来浏览对象的属性并验证它们。但我对收藏财产有意见。我可以确定它是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:很抱歉你们浪费时间

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

IEnumerable lst = model as IEnumerable;
if(lst != null)
{
    //loop
}

如果模型实现了IEnumerable,这应该会起作用。

以下操作将引发无效的强制转换异常:

IEnumerable lst = (IEnumerable) model;