Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么列表声明在c中不起作用#_C#_List_Variable Declaration - Fatal编程技术网

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预期的方式工作,它仍然会破坏他的程序,因为只有一个列表对象和三个对它的引用。另外,请注意,公共字段被认为是不好的做法。你最好把它们变成公共财产。