【发布时间】:2019-10-26 22:24:51
【问题描述】:
我有一堂课,里面有一些静态字段。当它们被初始化时,它们会将自己添加到字典中。
当程序第二次启动时,它会尝试访问字典的内容,但由于我没有访问类中的任何字段(字典在另一个),所以找不到它们。
我已经明白,当我访问其中一个静态字段时会初始化它们,但是是否有任何其他方法可以初始化它们而无需无缘无故调用任何方法或字段,然后将它们初始化一次?
----------
这里有一些代码:
资源.cs
public class Resource : InventoryItem
{
public const int IDBase = 1000000;
private Resource(int id) : base(IDBase + id) { }
public static Resource Hydrogen { get; } = new Resource(1); // H
public static Resource Helium { get; } = new Resource(2); // He
public static Resource Lithium { get; } = new Resource(3); // Li
public static Resource Beryllium { get; } = new Resource(4); // Be
public static Resource Boron { get; } = new Resource(5); // B
public static Resource Carbon { get; } = new Resource(6); // C
public static Resource Nitrogen { get; } = new Resource(7); // N
public static Resource Oxygen { get; } = new Resource(8); // O
// and all the other elements....
}
}
InventoryItem.cs
public abstract class InventoryItem
{
public int ID { get; }
private static readonly Dictionary<int, InventoryItem> idList = new Dictionary<int, InventoryItem>();
public InventoryItem(int id)
{
ID = id;
idList[id] = this;
}
public static InventoryItem GetFromID(int id)
{
return idList[id];
}
}
当我在从 Resource 类访问任何内容之前使用 InventoryItem.GetFromID(int id) 时,字典是空的,什么也找不到。如果我在字典中之前访问任何资源。
【问题讨论】:
标签: c# static initialization