在Linq查询中使用SortedList
时,包含null
的某些对象星座会引用设置为let
的列表。
这是一个最低限度的工作示例。其中大部分内容只是为了确保它能够反映我正在从事的工作;重要的部分是在最后一行,因NullReferenceException
为testList["1"].Elements
而引发null
。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TypecastTest {
public abstract class ComplexBase { }
public abstract class ComplexClass : ComplexBase {
internal SortedList<string, ComplexElement> Elements { get; set; }
}
public abstract class ComplexElement : ComplexBase { }
public class ComplexClassA : ComplexClass {
internal new SortedList<string, ComplexElementA> Elements { get; set; }
public ComplexClassA() {
Elements = new SortedList<string, ComplexElementA>();
}
}
public class ComplexElementA : ComplexElement { }
public class ComplexClassB : ComplexClass {
internal new SortedList<string, ComplexElementB> Elements { get; set; }
public ComplexClassB() {
Elements = new SortedList<string, ComplexElementB>();
}
}
public class ComplexElementB : ComplexElement { }
public class TheBigCollection {
internal SortedList<string, ComplexClass> Classes { get; set; }
public TheBigCollection() {
Classes = new SortedList<string, ComplexClass>();
}
}
class Program {
static void Main(string[] args) {
ComplexClassA ccA1 = new ComplexClassA();
ComplexElementA ceA1a = new ComplexElementA();
ComplexElementA ceA1b = new ComplexElementA();
ccA1.Elements.Add("A1a", ceA1a);
ccA1.Elements.Add("A1b", ceA1b);
ComplexClassA ccA2 = new ComplexClassA();
ComplexElementA ceA2a = new ComplexElementA();
ComplexElementA ceA2b = new ComplexElementA();
ccA2.Elements.Add("A2a", ceA2a);
ccA2.Elements.Add("A2b", ceA2b);
ComplexClassB ccB1 = new ComplexClassB();
ComplexElementB ceB1a = new ComplexElementB();
ComplexElementB ceB1b = new ComplexElementB();
ccB1.Elements.Add("B1a", ceB1a);
ccB1.Elements.Add("B1b", ceB1b);
ComplexClassB ccB2 = new ComplexClassB();
ComplexElementB ceB2a = new ComplexElementB();
ComplexElementB ceB2b = new ComplexElementB();
ccB2.Elements.Add("B2a", ceB2a);
ccB2.Elements.Add("B2b", ceB2b);
TheBigCollection tbc = new TheBigCollection();
tbc.Classes.Add("1", ccA1);
tbc.Classes.Add("2", ccA2);
tbc.Classes.Add("3", ccB1);
tbc.Classes.Add("4", ccB2);
var query = from kvp in tbc.Classes
let tmp = new {
tmpKey = kvp.Key,
tmpValue = kvp.Value
}
select tmp;
Dictionary<string, ComplexClass> testDictionary = query.ToDictionary(x => x.tmpKey, x => x.tmpValue);
SortedList<string, ComplexClass> testList = new SortedList<string, ComplexClass>(testDictionary);
int test = testList["1"].Elements.Count;
}
}
}
为什么这是null
?在let
中生成匿名对象会阻止正确复制引用会发生什么?