转换匿名类型会抛出转换错误

时间:2011-12-27 15:20:19

标签: c# asp.net casting type-conversion

在我创建的Global.asax文件中,我创建了包含匿名类型对象的数组列表

Application["userRecordsCountList"] = new ArrayList();

((System.Collections.ArrayList)Application["userRecordsCountList"]).Add(new { userCount = 12, logTime = DateTime.Now });

现在在我的cs文件中我有一个像这样的

的转换函数
T Cast<T>(object obj, T type)
{
    return (T)obj;
}

现在当我运行循环迭代数据并提取数据集中的数据时,我得到一个错误 看到代码

ArrayList countRecord = new ArrayList((System.Collections.ArrayList)Application["userRecordsCountList"]);

foreach (var item in countRecord)
    {
        dr = dt.NewRow();
        var record = Cast(item, new { userCount = "", logTime = "" });
        dr["Time"] = record.logTime;
        dr["Users"] = record.userCount;
        dt.Rows.Add(dr);
    }

错误是

Unable to cast object of type '<>f__AnonymousType0`2[System.Int32,System.DateTime]' to type '<>f__AnonymousType0`2[System.String,System.String]'.

请帮帮我..我已经尝试过在stackoverflow或任何其他来源找到的每种方法.....

日Thnx

3 个答案:

答案 0 :(得分:6)

不要使用匿名类型 - 使用您需要的实际类型。匿名类型只能在方法中使用 - 它们不能作为参数返回类型传递,并且通常不适合序列化。

此外,您不应使用ArrayList - 它不是类型安全的。请改用List<T>之类的通用集合。

答案 1 :(得分:0)

他们不兼容类型。错误消息给出错误。一种是具有intDateTime属性的匿名类型。第二个是stringstring作为属性。

您只能转换为实际类型或基类,而匿名类型不具有object以外的基类,这样您才可以投射它们到。

这可能是你想要的:

    dr = dt.NewRow();
    dr["Time"] = item.logTime.ToString();
    dr["Users"] = item.userCount.ToString();
    dt.Rows.Add(dr);

或者如Oded所说,使用真实的类型。

答案 2 :(得分:0)

您的代码中演示的那个不是Anonymous类型的理想示例。我宁愿对方法级范围使用匿名类型,最好使用一些Linq。

虽然我同意为每个对象组合创建一个类/模型很麻烦。因此,在您的情况下,您可以考虑使用通用Pair类,只是为了在配对对象中存储DateTime和int。阅读here

所以,你的收藏将成为:

(List<Pair<int,DateTime>>Application["userRecordsCountList"]).Add(new Pair<int,DateTime>(12, DateTime.Now)); 
相关问题