我有两个要同步的简单列表。
List<Guid> untrackedList包含一堆 Guid。
List<Foo> trackedList包含许多对象Foo(其中包括)具有 Guid 的 ID 属性。此列表由实体框架跟踪,因此我想为 untrackedList 中存在但尚未在 trackedList 中的那些添加新项目,并从 trackedList 中删除所有未出现在 untracked List 中的内容。
public void MyTestMethod()
{
const int someThing = 1000;
var untrackedList = new List<Guid>()
{
new Guid("8fcfb512-ca00-4463-b98a-ac890b3ac4da"),
new Guid("6532b60b-f047-4a96-9e5f-c5a242f9a1f5"),
new Guid("103cb7e4-1674-490c-b299-4b20d90e706c"),
new Guid("6c933cce-fb0e-4e1b-bbc3-e62235933cc8")
};
var trackedList = new List<Foo>()
{
new Foo() { SomeId = new Guid("6532b60b-f047-4a96-9e5f-c5a242f9a1f5"), Something = someThing },
new Foo() { SomeId = new Guid("12345678-abcd-1234-1234-1234567890ab"), Something = someThing }
};
// testing Find and Exists
var testFind = trackedList.Find(x => x.SomeId == new Guid("6532b60b-f047-4a96-9e5f-c5a242f9a1f5")); // finds one Foo
var testExists = trackedList.Exists(x => x.SomeId == new Guid("12345678-abcd-1234-1234-1234567890ab")); // == true
foreach (var guid in untrackedList)
{
// add all items not yet in tracked List
if (!trackedList.Exists(x => x.SomeId == guid))
{
trackedList.Add(new Foo() { SomeId = guid, Something = someThing });
}
}
// now remove all from trackedList that are not also in untracked List (should remove 12345678-...)
trackedList.RemoveAll(x=> !untrackedList.Contains(x.SomeId)); // successful, but also shows CS0103 in the debugger
}
Run Code Online (Sandbox Code Playgroud)
这可能不是最有效的方法,但它似乎有效。但是,当通过调试器运行它时,我被错误 CS0103“当前上下文中不存在名称 'x'”所抛弃

是什么导致了这个错误?为什么它不会导致异常?
.RemoveAll 方法(最后一行)的调试器中显示了相同的错误。
小智 0
很简单,通常当变量不是范围且无法计算时会发生错误,这就是如果编译器尝试计算 x 会发生什么,x 并不是在方法 MyTestMethod 的范围内真正计算的,有一个表达式构建自查询和计算在不同的范围内,因为 x 是表达式的一部分,所以它在不同的范围内计算。