gpt4 book ai didi

c# - 静态对象为空/未在正确时间初始化

转载 作者:行者123 更新时间:2023-11-30 12:25:11 25 4
gpt4 key购买 nike

我正在使用 type-safe enum pattern在这里概述。我需要将一个类型安全的枚举嵌套到另一个枚举中。在创建父构造函数时,子属性(静态对象)为 NULL。似乎子构造函数没有被调用,我遇到了一些错误。(父子关系我很困惑,但它解释了层次结构)

这是一个例子(我正在使用 netMF):

public class MyDeviceSetting //parent
{
public readonly string Name;
public MyUnit SettingUnit;
public readonly MyUnit.UnitPurpose UnitPurpose;

#region MY STATIC SETTINGS
//UNIT SETTINGS
public static MyDeviceSetting TempUnits = new MyDeviceSetting("TempUnits", MyUnit.mm); //MyUnit.mm is null. Why?
public static MyDeviceSetting BLAH = new MyDeviceSetting("BLAH", MyUnit.inch);//MyUnit.inch is null. Why?
#endregion



/// <summary>
/// This is the MAIN PRIVATE Constructor
/// </summary>
/// <param name="?"></param>
private MyDeviceSetting(string name, MyUnit defaultUnit)
{
Name = name;
SettingUnit = defaultUnit;//NULL
UnitPurpose = SettingUnit.Purpose; //fails because SettingUnit is NULL


}


}


public sealed class MyUnit
{
private static int Count = 0;

//these are used to store and identify the unit in memory
public readonly int UnitID;
public readonly int TestID;

public enum UnitPurpose
{
DISTANCE,
SPEED,
TEMPERATURE,
TIME,
CLOCK,
NO_UNITS
}

public readonly string DisplayName;
public readonly string Abbreviation;
public readonly string Name;
public readonly UnitPurpose Purpose;

#region My Units
public static readonly MyUnit mm = new MyUnit("Milimeters", "mm", "mm", UnitPurpose.DISTANCE, 1);
public static readonly MyUnit inch = new MyUnit("inch", "inch", "in", UnitPurpose.DISTANCE, 2);



#endregion

private MyUnit(string name,
string displayName,
string abbreviation,
UnitPurpose unitPurpose,
int unitID)
{
Name = name;
DisplayName = displayName;
Abbreviation = abbreviation;
Purpose = unitPurpose;
UnitID = unitID;
TestID = Count;
Count++;

}


}

如何确保 child 不为空?有解决方法吗?编辑:This Post确保这应该可以正常工作,但就我而言,它不起作用。 Null

最佳答案

这似乎是 .Net Micro 框架的错误/限制。它不完全支持静态构造函数。这是报告相同问题的人:https://msdn.microsoft.com/en-us/library/Cc533032.aspx

documentation对于 NetCF 3.0 包含以下警告:

Do not use static constructors. They are not yet fully supported by the .NET Micro Framework.

从这里blog post似乎还说(至少从 2.0 开始)对静态构造函数的调用是序列化的:

There are some things that cannot be done in .NET Compact Framework in a static constructor which are possible in the full .NET Framework. Basically, all static constructors when are executed in a serialized fashion in .NET Compact Framework V2

那篇文章在死锁的背景下讨论了它,但我相信这就是它不起作用的原因。

不幸的是,这意味着您不能依赖静态,而必须自己处理初始化和锁定。这样的事情应该有效:

private static MyUnit inch;

public static MyUnit Inch
{
get
{
if (inch == null)
inch = new MyUnit("inch", "inch", "in", UnitPurpose.DISTANCE, 2);
return inch;
}
}

不幸的是,这失去了静态构造函数为您提供的线程安全性。这将很难修复,因为您不能依赖静态成员,因为正如我们所见,您不能依赖它们的初始化。

关于c# - 静态对象为空/未在正确时间初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31971824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com