c#-无法使用一个实例变量来初始化另外一个实例变量

如果你要用一个string数组作为参数来初始化另外一个LinkedList链表,那你肯定是要确保string数组要先实例化完成的,如果只是简单的这样写

    int[,] multiarray = { { 1, 3, 4 }, { 2, 4, 5 } };
    string[] words = { "I","C","E","C","O","N","C","G"};
    List<string> listtest = new List<string>();
    LinkedList<string> link = new LinkedList<string>(words);

,编译器是无法保证words是在list前面初始化完成,所以要会得到这样的错误NullReferenceException.,此时就可以把words设为静态变量就行了,因为静态变量是一定比实例变量先加载的,或者如果是在unity脚本的话,可以把LinkedList<string> link = new LinkedList<string>(words)放在start()方法里面,因为start方法前的成员变量一定会先加载完。

A field initializer cannot reference the nonstatic field, method, or property

猜你喜欢

转载自blog.csdn.net/icecoldless/article/details/81088291