在struct中初始化只读静态字段的最佳方法是什么?据我所知,我们可以在构造函数中或声明后立即初始化只读字段,但是我不确定何时将调用静态构造函数或在结构中初始化静态只读字段。例如:
public readonly struct Either<T1, T2>
{
private static readonly StrategyType Strategy =
Either.IsSmth() ? StrategyType.Strategy1 : StrategyType.Strategy2;
private readonly object _ref;
private Either(object @ref)
{
_ref = @ref;
}
public static implicit operator Either<T1, T2>(T1 value)
{
if(Strategy == StrategyType.Strategy1)
return new Either<T1, T2>();
// ...code
}
public static implicit operator Either<T1, T2>(T2 value) { // ...code }
}
或
public readonly struct Either<T1, T2>
{
private static readonly StrategyType Strategy;
static Either()
{
Strategy = Either.IsSmth() ? StrategyType.Strategy1 : StrategyType.Strategy2;
}
public static implicit operator Either<T1, T2>(T1 value) { // ...code }
public static implicit operator Either<T1, T2>(T2 value) { // ...code }
}
此结构的用法:
Either<int, string> either = "test";
或
Either<TestClass1, TestClass2> either = new TestClass1{ TestIntProp = 100 };
“策略”字段的代码无效,并且使用默认值初始化。