C#无法更改静态泛型类中的静态字段

时间:2016-01-26 15:15:51

标签: 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 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
    }
}

有人可以向我解释为什么Test<int>.d在分配值后仍为0List为空?

1 个答案:

答案 0 :(得分:3)

以下代码适用于我。

 Test<int>.d = 17;
 int seventeen = Test<int>.d;

请注意TestTest<T>不同,您只需为Test<int>.d分配一个int值。