C#无法更改静态泛型类中的静态字段
这是在Unity游戏引擎中,尽管我不确定这是c#的东西还是Unity特有的C#无法更改静态泛型类中的静态字段,c#,generics,unity3d,null,C#,Generics,Unity3d,Null,这是在Unity游戏引擎中,尽管我不确定这是c#的东西还是Unity特有的 //This is fine, I can assign variables to these static fields as you would expect public static class Test { public static List list = new List(); public static int d = 0; } //Field in this class are alw
//This is fine, I can assign variables to these static fields as you would expect
public static class Test
{
public static List list = new List();
public static int d = 0;
}
//Field in this class are always default, even after assigning values in another class
public static class Test<T>
{
public static List<T> list = new List<T>();
public static int d = 0;
}
public class TestClass2: MonoBehaviour
{
private void TestMethod()
{
Test<int>.d = 3;
Test<string>.list.Add("Hi");
//Both are still null, even after declaring and assigning
}
}
//这很好,我可以像您期望的那样为这些静态字段分配变量
公共静态类测试
{
公共静态列表=新列表();
公共静态int d=0;
}
//此类中的字段始终为默认值,即使在为另一个类赋值之后也是如此
公共静态类测试
{
公共静态列表=新列表();
公共静态int d=0;
}
公共类TestClass2:单一行为
{
私有void TestMethod()
{
试验d=3;
测试列表。添加(“Hi”);
//即使在声明和赋值之后,两者仍然为null
}
}
有人能给我解释一下为什么
Test.d
在赋值后仍然是0
并且List
是空的吗?下面的代码适合我
Test<int>.d = 17;
int seventeen = Test<int>.d;
Test.d=17;
int 17=测试d;
请记住,
Test
和Test
不是一回事,您只需将int值赋值给Test.d
,您需要在静态构造函数中赋值。如果list
为null
,则,调用Add
时,您会得到一个NullReferenceException
。int
不能为空,因此您的问题基于错误的假设。您错了,错了。@JerrySwitalskilist
和d
正在静态构造函数中赋值。这就是如何编译字段上的初始值设定项@Dennis_E是否抛出NullReferenceException
并不能解决这个问题@Martin Mazza DawsonTest.d
仍然不是零。是3。谢谢当我将鼠标悬停在intellisence上进行测试时,它仍然是0。但当把它分配给17个变量时,它确实起作用。我不知道这是为什么。这是因为静态成员变量直到第一次被初始化时才被初始化accessed@MartinMazzaDawson你在第一行设置断点了吗?如果是这样,它还没有执行,在那一点上,d仍然是0。@Dennis_E即使在完全遍历代码时,我的intellisence说它仍然是0,但将它赋给int-seven会给变量正确的值17。我想这是使用Unity时智能上的一个缺陷。