为什么下面的代码会编译,但会抛出NullReferenceException?列表中的空例外<T>初始化
using System.Collections.Generic;
class Program
{
static void Main()
{
C c = new C { P = { "" } };
}
}
class C
{
public List<string> P;
}
为什么下面的代码会编译,但会抛出NullReferenceException?列表中的空例外<T>初始化
using System.Collections.Generic;
class Program
{
static void Main()
{
C c = new C { P = { "" } };
}
}
class C
{
public List<string> P;
}
基本上代码
C c = new C { P = { "" } };
是
C temp = new C();
temp.P.Add("");
C c = temp;
,所以它不是创建列表,只是想添加到它,因此运行时错误真的很短的手,但没有编译错误。
使用系统; using System.Collections.Generic; public class Program { public static void Main(string [] args) {c} = new C {P = {“b”}}; Console.WriteLine(c.P.Count); } } class C { public list
在我看来,语法糖太混乱了。如果你写'C c = new C {P = new List
@CsuporJenő问题是关于它编译的原因,但导致一个异常,而不是如何解决它,使其不会引起异常。 – juharr
其符合的原因是因为
C c = new C { P = { "" } };
是有效的C#。
它只在运行时检查P是否为空 - 因此运行时为NullReferenceException。
因为'C'中的'P'为空,所以你试图赋给'P = {“”}' – Liam
因为P的状态直到运行时才知道。您可以拥有实例化对象的代码。从编译器的角度来看,它检查对象是否正确,而不是它存在。编译器无法遍历整个代码库中的每个逻辑树 – Liam
@juharr编译器如何知道(一般情况下)C的构造函数是否将“P”设置为任何值? – hvd