c# - 为什么列表声明在 c# 中不起作用
问题描述
我正在尝试像下面的代码一样声明列表。
public List<string> t1,t2,t3 = new List<string>();
当我尝试将某些内容添加到 List 时,它会给我在运行时为 null 的错误,但不会给我编译时错误。
public List<string> t1 = new List<string>();
public List<string> t2 = new List<string>();
public List<string> t3 = new List<string>();
虽然个人声明工作完美。
请有人解释一下,并在此先感谢您。
解决方案
如果它们的类型相同,您可以在一行中声明多个变量,如下所示:
// Declare and initialize three local variables with same type.
// ... The type int is used for all three variables.
//
int i = 5, y = 10, x = 100;
Console.WriteLine("{0} {1} {2}", i, y, x);