dan*_*tel 24 c# enums coding-style
我主要是C++背景,我正在学习C#.所以,我需要一些C#习语和风格的帮助.
我试图在C#中编写一个小型文本文件解析方法,其中我需要一个具有三种状态的简单状态变量.在C++中,我会enum为状态变量声明如下:
enum { stHeader, stBody, stFooter} state = stBody;
Run Code Online (Sandbox Code Playgroud)
...然后在我的解析循环中使用它,如下所示:
if (state == stHeader && input == ".endheader")
{
state = stBody;
}
Run Code Online (Sandbox Code Playgroud)
在C#中,我意识到无法enum在方法中声明内部.那么,为了清洁风格,我应该做些什么呢?enum在方法之外声明这个内部?使用幻数1,2,3?为此创建一个单独的类?
请帮我澄清一下我的困惑.
Wil*_*mpt 29
您可以获得的最接近的是类中的私有嵌套枚举:
public class TheClass
{
private enum TheEnum
{
stHeader,
stBody,
stFooter
}
// ...the rest of the methods properties etc...
}
Run Code Online (Sandbox Code Playgroud)
你也可以使用常量变量,但我更喜欢,我认为使用Enums是更好的代码风格
public class Class1
{
private enum TheEnum
{
stHeader,
stBody,
stFooter
}
public void SomeMethodEnum()
{
TheEnum state = TheEnum.stBody;
switch (state)
{
case TheEnum.stHeader:
//do something
break;
case TheEnum.stBody:
break;
case TheEnum.stFooter:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
public void SomeMethodConst()
{
int state = 1;
const int Header = 1;
const int Body = 2;
const int Footer = 3;
switch (state)
{
case Header:
break;
case Body:
break;
case Footer:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
Run Code Online (Sandbox Code Playgroud)