我正在尝试像 LinqPad 一样使用 Roslyn,但我正在使用完全有效的 C# 代码片段并且被告知它们是无效的。考虑这种沼泽标准实用方法。
public static class EnumConvert<TEnum, TUnderlying>
where TEnum : struct,IFormattable, IConvertible, IComparable
where TUnderlying : struct,IFormattable, IConvertible, IComparable, IComparable<TUnderlying>, IEquatable<TUnderlying>
{
public static readonly Converter<TEnum, TUnderlying> ToUnderlying;
public static readonly Converter<TUnderlying, TEnum> ToEnum =
Init(out ToUnderlying);
private static Converter<TUnderlying, TEnum> Init(out Converter<TEnum, TUnderlying> underlier)
{
if (Type.GetTypeCode(typeof(TEnum)) != Type.GetTypeCode(typeof(TUnderlying)) ||
typeof(TEnum) == typeof(TUnderlying))
{
throw new ArgumentException("TEnum does not derive from TUnderlying");
}
Func<TUnderlying, TUnderlying> Identity = x => x;
underlier = Delegate.CreateDelegate(typeof(Converter<TEnum, TUnderlying>), Identity.Method) as Converter<TEnum, TUnderlying>;
return Delegate.CreateDelegate(typeof(Converter<TUnderlying, TEnum>), Identity.Method) as Converter<TUnderlying, TEnum>;
}
}
Roslyn 声称我调用 out 参数是无效的ToUnderlying
。
在你问我为什么不使用静态构造函数之前,我想确保我beforefieldinit
在我的类上保留了类属性。否则,我将支付每次访问该方法时初始化它的费用。在 C# 中,这被认为是有效的,但 Roslyn 告诉我(6,76): error CS0199: A static readonly field cannot be passed ref or out (except in a static constructor)