c# - 作为函数结果的枚举值

标签 c#

我有三个枚举:

enum ValueType : int
{
  FloatingPoint = 2,
  .../...
}
enum ConstraintType : int
{
  Range = 2,
  .../...
} 
enum Parameter : int 
{
  ExposureTime = F(ValueType.FloatingPoint, ConstraintType.Range, 23),
  .../...
}

问题出在 F 的签名上,如果我使用:

private static int F(ValueType _V, ConstraintType _C, int _N) { ... }

Parameter 定义中的每次调用都会出现错误(无效参数),但如果我改用以下代码:

private static int F(int _V, int _C, int _N) { ... }

一切都很好。

这不是阻塞问题,但我想了解为什么会这样。

最佳答案

C# 规范在第 14.3 节(“枚举成员”)中声明

Within an enum member initializer, values of other enum members are always treated as having the type of their underlying type, so that casts are not necessary when referring to other enum members.

据我所知,这就是参数似乎具有 int 类型的原因。有趣的是,这不会导致无效参数错误:

ExposureTime = F((ValueType)ValueType.FloatingPoint, 
                 (CostraintType)ConstraintType.Range,
                 23),

当然它仍然会导致另一个错误,因为您不能像 Marc 所说的那样使用方法调用来初始化枚举成员。方法调用不是常量表达式,而

The associated value of an enum member is assigned either implicitly or explicitly. If the declaration of the enum member has a constant-expression initializer, the value of that constant expression, implicitly converted to the underlying type of the enum, is the associated value of the enum member. If the declaration of the enum member has no initializer, its associated value is set implicitly [...]

关于c# - 作为函数结果的枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11306014/

相关文章:

c# - Web api中的重复键问题

c# - 继承自动实现的属性,在派生类中只需要 getter

c# - 确定图像是否模糊

c# - 属性 : Internal get, 保护集

c# - 小数加倍

c# - 十六进制值 0x00 是加载 XML 文档的无效字符

c# - WPF 自动调整元素大小

c# - .NET 4.0 并发收集性能

c# - HttpWebRequest 和 Uri 改变 requestUri

c# - ASP.NET 3.5 网络服务