我知道这听起来有点奇怪,但我想将一个
我知道在将值类型强制转换之前将其转换为对象(
因此,我的问题是:实现这种通用行为的最佳方法是什么?
T?
对象转换为int?
。我之所以这样做是因为T
总是枚举类型,并且我知道此枚举类型可以转换为int。我正在创建一个通用的枚举包装类,并找到这个“解决方案”将通用类型限制为枚举类型。
我的代码目前看起来像这样:
public class EnumWrapper<T>
where T : struct, IConvertible
{
public EnumWrapper()
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumerated type");
}
}
public T? Enum { get; set; }
public int? EnumValue => (int?)Enum; // this won't compile
...
}
我知道在将值类型强制转换之前将其转换为对象(
(int?)(object)Enum
)可以欺骗编译器,但这种方法对这里是否有效我还有疑问,我怀疑可空类型会干扰它。因此,我的问题是:实现这种通用行为的最佳方法是什么?
public int? EnumValue => this.Enum?.ToInt32(CultureInfo.CurrentCulture.NumberFormat);
- haim770