C# 为什么列表声明在c中不起作用#
我正试图声明如下代码所示的列表C# 为什么列表声明在c中不起作用#,c#,list,variable-declaration,C#,List,Variable Declaration,我正试图声明如下代码所示的列表 公共列表t1、t2、t3=新列表() 当我尝试向列表中添加某些内容时,它会在运行时给我错误was null,但不会给我编译时错误 public List<string> t1 = new List<string>(); public List<string> t2 = new List<string>(); public List<string> t3 = new List<string>()
公共列表t1、t2、t3=新列表()代码>
当我尝试向列表中添加某些内容时,它会在运行时给我错误was null,但不会给我编译时错误
public List<string> t1 = new List<string>();
public List<string> t2 = new List<string>();
public List<string> t3 = new List<string>();
public List t1=new List();
公共列表t2=新列表();
公共列表t3=新列表();
而个人宣言则是完美的
请有人解释一下,并提前向您表示感谢。如果变量类型相同,您可以在一行中声明多个变量,如下所示:
// 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);
没有什么需要解释的,这是基本的C#语法。使用t1,t2,t3=new…
时,您仅将新引用分配给t3
,而不是分配给t1
,也不是分配给t2
。要实现这一点,您需要在第一个示例中使用public List t1=new List,您只需以相同的方式初始化t3
?int a,b,c=3代码>仅将c
初始化为3
,但a
和b
仍为0
(默认值)。或者实际上它们是未初始化的。@Flater:实际上。。。即使它按照OP预期的方式工作,它仍然会破坏他的程序,因为只有一个列表对象和三个对它的引用。另外,请注意,公共字段被认为是不好的做法。你最好把它们变成公共财产。