声明静态枚举的麻烦,C#

Ray*_*ess 57 c# enums static

嗨,我试图像这样声明一个静态枚举:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Lds.CM.MyApp.Controllers
{
    public class MenuBarsController : Controller
    {
        // Menu Bar enums
        public static enum ProfileMenuBarTab { MainProfile, Edit, photoGallery }

        public ActionResult cpTopMenuBar(string tabSelected)
        {
            ...            
Run Code Online (Sandbox Code Playgroud)

"但我收到以下错误:"修饰符'静态'对此项无效."我知道这很简单,但我似乎无法看到问题.非常感谢!

mag*_*tic 119

枚举是类型,而不是变量.因此,根据定义,它们是"静态的",您不需要关键字.

public enum ProfileMenuBarTab { MainProfile, Edit, PhotoGallery }
Run Code Online (Sandbox Code Playgroud)

  • 根据定义,枚举是“静态”的,但我们不能在静态类中使用它,为什么? (2认同)

SLa*_*aks 12

拿出来static.
枚举是类型,而不是成员; 没有静态或非静态枚举的概念.

您可能正在尝试创建类型的静态字段,但这与类型声明无关.
(虽然你可能不应该制作静态字段)

此外,您不应该创建public嵌套类型.


Tar*_*rik 6

您不需要将其定义为static.当编译枚举类型时,C#编译器会将每个符号转换为该类型的常量字段.例如,编译器将前面显示的Color枚举视为编写了类似于以下内容的代码:

internal struct Color : System.Enum {
            // Below are public constants defining Color's symbols and values
            public const Color White  = (Color) 0;
            public const Color Red    = (Color) 1;
            public const Color Green  = (Color) 2;
            public const Color Blue   = (Color) 3;
            public const Color Orange = (Color) 4;
            // Below is a public instance field containing a Color variable's value
            // You cannot write code that references this instance field directly
            public Int32 value__;
}
Run Code Online (Sandbox Code Playgroud)