在基本静态构造函数中显式调用静态构造函数

时间:2019-03-21 22:12:25

标签: c# generics static static-methods static-members

这有点古怪/复杂,只是好奇心比什么都重要。

我一直在寻找一种方法,以确保来自基类的静态调用可以安全地使用派生类中设置的静态信息。然后我注意到C#允许我在基类静态构造函数中调用派生类静态构造函数。

我的问题:在基类静态构造函数中调用派生类静态构造函数是安全的

以下是一些示例代码:

public abstract class Enumeration<TEnum, TValue>
    where TEnum : Enumeration<TEnum, TValue> // << Note the CRTP-ish thing
    where TValue: class
{
    private static readonly Dictionary<string, Enumeration<TEnum, TValue>> Mapping = new Dictionary<string, Enumeration<TEnum, TValue>>();
    public TValue Value { get; }
    public string Name { get; }

    // Base class calling derived static constructor. This sets up "Mapping" with derived class enumerations
    static Enumeration()
    {
        System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(TEnum).TypeHandle);
    }

    // Static member "Mapping" filled using this constructor when derived class statics are initialized
    protected Enumeration(TValue enumValue, string name)
    {
        Value = enumValue;
        Name = name;
        Mapping.Add(name, this);
    }

    // Uses "Mapping", so "Mappings" needs to be filled before this is called.
    protected static IEnumerable<TEnum> All => Mapping.Values.AsEnumerable().Cast<TEnum>();

    public override string ToString() { return Name; }
}

public sealed class DerivedEnum : Enumeration<DerivedEnum, String>
{
    // This static member will input itself into the static "Mapping" in the base class
    public static readonly DerivedEnum A = new DerivedEnum("A", "A");

    private DerivedEnum(string val, string name) : base(val, name) {}
}

我已经完成了几项基本测试,但似乎还没有损坏。有办法解决这个问题吗?

如果您需要...这里是一个小提琴:https://dotnetfiddle.net/mREPyL

此外,我的代码受this answer的启发。我想看看是否可以使派生类更简洁。

0 个答案:

没有答案
相关问题