在C#中的方法中定义枚举? [英] Define enums within a method in C#?

查看:538
本文介绍了在C#中的方法中定义枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我主要有一个C ++背景,我正在学习C#。所以,我需要一些帮助C#的习语和风格。

I have mainly a C++ background and I am learning C#. So, I need some help with C# idioms and style.

我想在C#中写一个小的文本文件解析方法,其中我需要一个简单的状态变量具有三个状态。在C ++中,我将为状态变量声明一个 enum

I am trying to write, in C#, a small text-file parsing method in which I need a simple state variable with three states. In C++ I would declare an enum like this for the state variable:

enum { stHeader, stBody, stFooter} state = stBody;

...然后在我的解析循环中使用它:

...and then use it in my parsing loop like this:

if (state == stHeader && input == ".endheader")
{
  state = stBody;
}



在C#中我意识到不可能声明一个 enum 。所以,我应该为清洁风格做什么?在方法外声明这个内部枚举?使用魔法数字1,2,3?为此创建一个单独的类?

In C# I realize that it is not possible to declare an enum inside a method. So, what I am supposed to do for sake of clean style? Declare this internal enum outside of the method? Use magic numbers 1,2,3? Create a separate class for this?

请帮助我清除混乱。

推荐答案

您可以得到的最接近的是类中的私有嵌套枚举:

The closest you can get is a private nested enum with in the class:

public class TheClass
{
    private enum TheEnum 
    {
       stHeader, 
       stBody, 
       stFooter
    }

    // ...the rest of the methods properties etc... 
}

这篇关于在C#中的方法中定义枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆