【发布时间】:2010-09-27 14:12:52
【问题描述】:
我有点难以理解这里的问题所在。我有一些代码使用 LINQ 从数据库中提取记录并将它们放入一个对象中,该对象被转换为一个接口。有点像这样:
public IEnumerable<ISomeObject> query()
{
return from a in dc.SomeTable
select new SomeObject
{
//Assign various members here
} as ISomeObject;
}
当我对此进行测试时,我将返回的 IEnumerable 放入一个名为 results 的变量中并运行这一行:
Assert.AreEqual(EXPECTED_COUNT, results.Count());
当它运行时,我得到一个 System.Security.VerificationException: "Operation could destabilize the runtime."
我找到了解决方案here,是这样的:
var results = from a in dc.SomeTable
select new SomeObject
{
//Assign various members here
} as ISomeTable;
return results.OfType<ISomeObject>();
这可行,但我无法理解这里发生了什么。为什么我首先得到异常,上面的代码行是如何修复它的? MSDN 文档似乎表明这是一个类型安全问题,但我没有看到以前的代码在哪里是类型不安全的。
更新 我发现了更多信息。如果我将返回类型设为 IQueryable,则第一个示例有效。这让 what 出了点问题有了更多的了解,但我仍然对 why 感到困惑。为什么编译器不强制我将 IEnumerable 转换为 IQueryable?
【问题讨论】:
-
当我将ANTS Performance Profiler 用于使用HtmlAgilityPack 的项目时,这种情况经常发生。对此的解决方案是通过将
<assemblyName>HtmlAgilityPack</assemblyName>添加到文件“C:\Users\YourUserName\AppData\Local\Red Gate\ANTS Performance Profiler 9\LineLevelBlacklist.xml”来解决tell the profiler to exclude HtmlAgilityPack(用您的实际用户替换“YourUserName”名称)。
标签: c# .net linq linq-to-sql .net-3.5