【问题标题】:How to assign enum to variable如何将枚举分配给变量
【发布时间】:2013-08-26 22:13:11
【问题描述】:

如何从声明的枚举中分配新变量

public enum FontStyle
{
 Regular = 0;
 Bold =1;
 Italic = 2
}
// dont know what Type to cast it :/
TYPE fontstyle = FontStyle.Bold;

我不确定要转换哪种类型,它包含在 System.Drawing 类中。

【问题讨论】:

  • FontStyle fontstyle = FontStyle.Bold
  • @Dshah 你确定吗?它不起作用或您的某些其他代码不起作用?
  • 它是相同的代码,我收到此错误“嵌入式语句不能是声明或标记语句”
  • @I4V - :) “也许它是懒惰的”应该在常见问题解答中作为回答“为什么它不起作用”的问题!
  • This is the compiler error you're getting。请注意描述中与您正在做的事情相匹配的任何内容?我只能在您的 enum 声明中发现应该是逗号的分号,但您显然没有足够的信息来确定这里的问题。

标签: c# .net


【解决方案1】:

它是FontStyle 类型,即枚举是一等类型。

public enum FontStyle
{
    Regular = 0;
    Bold =1;
    Italic = 2
}

// No need to cast it
FontStyle fontstyle = FontStyle.Bold;

编辑:也许你有这样的代码:

if(1 == 1)
    FontStyle fontstyle = FontStyle.Bold;    

对于您的错误(嵌入语句不能是声明或标记语句)将您的代码包围在块语句中,例如

if(1 == 1)
{
    FontStyle fontstyle = FontStyle.Bold;    
}

【讨论】:

    【解决方案2】:

    枚举类型,所以你的变量应该是FontStyle的类型:

    FontStyle fontstyle = FontStyle.Bold;
    

    【讨论】:

    • 谢谢,但我在上面使用时收到此错误嵌入式语句不能是声明或标记语句
    • @Dshah:我赌一美元你正在尝试做if (x) FontStyle f = whatever;,这是不合法的,因为然后你可以在哪里使用f你必须改为要么说FontStyle f = 0; if (x) f = whatever; 要么if (x) { FontStyle f = whatever; ... use f here ... }。更一般地说,如果你告诉人们你遇到了什么错误而不是说“它不起作用”,你会在这里得到更好的结果。通过在您的问题中包含相关详细信息来帮助试图帮助您的人。
    • 很抱歉,不知道是不是 if 语句造成的。我现在要发布完整的代码/错误详细信息,但在写作时我注意到 Plymouth223 回复并在我的代码周围添加了大括号。谢谢你的帮助,虽然我欠你一美元
    【解决方案3】:

    确保使用, 分隔枚举元素,而不是; ... 喜欢

    enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
    

    【讨论】:

      【解决方案4】:

      确保您的代码中没有混入类名和属性名...

          private void Form1_Load(object sender, EventArgs e)
          {
              // dont know what Type to cast it :/
              System.Drawing.FontStyle fontstyle = FontStyle.Bold;
              MessageBox.Show(fontstyle.ToString());
          }
      

      返回“粗体”:)...

      确保拥有

      使用 System.Drawing;

      并且您没有在您说无法创建枚举对象的同一位置声明枚举。

      【讨论】:

        猜你喜欢
        • 2014-09-20
        • 2016-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-09
        • 2013-06-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多