在我的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
发布于 2011-12-27 23:22:20
不要使用匿名类型-使用您需要的实际类型。匿名类型只能在方法中使用-它们不能作为参数或返回类型传递,通常不适合序列化。
此外,您不应该使用ArrayList -它不是类型安全的。改用像List<T>这样的泛型集合。
发布于 2011-12-27 23:26:06
它们不是兼容的类型。错误消息给出错误。一个是具有int和DateTime属性的匿名类型。第二个具有string和string属性。
您只能强制转换为实际类型或基类,而匿名类型除了object之外没有其他基类,因此这是您唯一可以将其强制转换的对象。
这可能就是你想要的:
dr = dt.NewRow();
dr["Time"] = item.logTime.ToString();
dr["Users"] = item.userCount.ToString();
dt.Rows.Add(dr);或者正如Oded所说,使用实数类型。
发布于 2011-12-27 23:58:44
在您的代码中演示的示例不是匿名类型的理想示例。对于方法级别的作用域,我更愿意使用匿名类型,最好是使用一些Linq。
虽然我同意为每个对象组合创建一个类/模型是很麻烦的。因此,在本例中,您可以考虑使用泛型Pair类,只需将DateTime和int存储在配对对象中即可。阅读here。
所以,你的收藏会变成:
(List<Pair<int,DateTime>>Application["userRecordsCountList"]).Add(new Pair<int,DateTime>(12, DateTime.Now)); https://stackoverflow.com/questions/8646224
复制相似问题