一般来说,我的理解是,类中的静态对象是在第一次引用类时构造的.然而,我正在经历一种我没有预料到的行为.
请考虑下面的类
public abstract class SmartColor<TColor> where TColor : SmartColor<TColor> {
private static readonly ConcurrentDictionary<string, TColor> _items = new();
protected SmartColor(string code, string name) {
Code = code;
Name = name;
//register all colors
foreach (var field in typeof(TColor).GetFields(BindingFlags.Public | BindingFlags.Static)) {
TColor? item = (TColor?)field.GetValue(null);
if (item is not null) {
Register(item);
}
}
}
public string Code { get; }
public string Name { get; }
public static TColor FromCode(string code) {
if (_items.TryGetValue(code, out var result)) {
return result;
}
return null;
}
private void Register(TColor item) {
_items.GetOrAdd(item.Code, item);
}
}
它又是从这个继承而来的
public class WebColor : SmartColor<WebColor> {
public static readonly WebColor White = new WebColor("#ffffff", nameof(White));
public static readonly WebColor Black = new WebColor("#000000", nameof(Black));
protected WebColor(string code, string name) : base(code, name) {
}
}
如果按如下方式使用,它将生成NullReferenceException
public static void Main()
{
WebColor color = WebColor.FromCode("#ffffff");
Console.WriteLine(color.Name);
}
我能理解为什么会发生这种事吗?小提琴here