在 C# 中,有没有办法同时定义枚举和该枚举的实例?
在 C# 中寻找代码优化,它允许我同时定义一个枚举并创建该枚举类型的变量:
之前:
enum State {State1, State2, State3};
State state = State.State1;
之后(不起作用):
enum State {State1, State2, State3} state;
state = State.State1;
是否存在类似的东西?
Looking for a code optimization in c# that allows me to both define an enum and create a variable of that enum's type simultaniously:
Before:
enum State {State1, State2, State3};
State state = State.State1;
After (doesn't work):
enum State {State1, State2, State3} state;
state = State.State1;
Does anything like that exist?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
C# 中不支持这一点,但如果您只需要切换某些状态并且不需要对其执行任何特殊操作,也许您可以解决此问题并通过使用元组或匿名类型执行“接近”枚举的操作。
例如,使用元组,您可以执行以下操作:
var someFakeEnum = Tuple.Create(0, 1);
UPDATE:
C# 7 引入了语法元组:
或者使用匿名类型:
var someFakeEnum = new { State1 = 0, State2 = 1 };
然后,您可以执行以下操作:
显然这不是一个实际的枚举,您没有 Enum 类型为您提供的糖分,但是您可以仍然使用二元运算符,如 OR、AND 或条件语句,如任何其他实际枚举。
There's no support for that in C#, but maybe you can workaround this and do something "near" to an enum by using tuples or anonymous types if you only need to switch some state and you don't need to do any special operations with it.
For example, using tuples, you can do this:
var someFakeEnum = Tuple.Create(0, 1);
UPDATE:
C# 7 has introduced syntactic tuples:
Or with anonymous types:
var someFakeEnum = new { State1 = 0, State2 = 1 };
And, after that, you can do something like:
Obviously this isn't an actual enumeration and you don't have the sugar that Enum type provides for you, but you can still use binary operators like OR, AND or conditionals like any other actual enumeration.
这不是优化。
不,不存在这样的优化,并且有充分的理由。它的可读性要差得多,而且这样做绝对没有任何好处。在两个单独的语句中声明它们并完成它。
如果您确实通过减少源代码中的行数而获得报酬,请像这样编写:
(是的,这是一个笑话。大多数情况下。)
This is not an optimization.
No, nothing like that exists, and for good reason. It's much less readable and there's absolutely zero benefit to be gained in doing so. Declare them in two separate statements and be done with it.
If you're literally getting paid to reduce the number of lines in your source code, write it like this:
(Yes, that's a joke. Mostly.)
我想是从 C/C++ 切换过来的吧?
不,不能那样做
Switching from C/C++, I suppose?
No, can't do that
不,那不存在。恕我直言,它的可读性也不是很好
No, that doesnt exists. Nor is it very readable IMHO
不,在 C# 中,声明或类型和使用该类型声明变量是分开的。
在 C/C++ 中,直接声明和使用类型是很常见的,例如使用 struct 关键字。在 C# 中它们是分开的。
请注意,在 C# 中,在声明
enum
(或class
或struct
)后不需要分号:但它仍然是允许的,大概是与 C/C++ 语法更兼容一点。
No, in C# the declaration or a type and using that type to declare variables are separate.
In C/C++ it's common to declare and use a type directly, for example with the
struct
keyword. In C# they are separate.Note that in C# you don't need the semicolon after declaring an
enum
(or aclass
or astruct
):It's still allowed though, presumably to be a little more compatible with C/C++ syntax.