如何将枚举赋值给变量

use*_*068 -5 .net c#

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

public enum FontStyle
{
 Regular = 0;
 Bold =1;
 Italic = 2
}
// dont know what Type to cast it :/
TYPE fontstyle = FontStyle.Bold;
Run Code Online (Sandbox Code Playgroud)

我不确定要使用哪个TYPE,它包含在System.Drawing类中.

Joe*_*oey 7

枚举类型,因此您的变量应该是以下类型FontStyle:

FontStyle fontstyle = FontStyle.Bold;
Run Code Online (Sandbox Code Playgroud)

  • @Dshah:我敢打赌你试图做的一美元`if(x)FontStyle f = what;`这不合法,因为*你可以在哪里使用`f`?*你必须改为说'FontStyle f = 0; if(x)f = whatever;`或`if(x){FontStyle f = what; ......在这里使用f ...}` 更一般地说,**如果你告诉人们你得到的是什么错误而不是说"它不起作用"**,你会在这里得到更好的结果**.通过在问题中包含相关详细信息,帮助那些试图帮助您的人. (2认同)

Ply*_*223 7

这是类型,FontStyle即枚举是一流的类型.

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

// No need to cast it
FontStyle fontstyle = FontStyle.Bold;
Run Code Online (Sandbox Code Playgroud)

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

if(1 == 1)
    FontStyle fontstyle = FontStyle.Bold;    
Run Code Online (Sandbox Code Playgroud)

对于您的错误(嵌入式语句不能是声明或带标签的语句),请在块语句中包含您的代码,例如

if(1 == 1)
{
    FontStyle fontstyle = FontStyle.Bold;    
}
Run Code Online (Sandbox Code Playgroud)