我有一门课叫问题(复数)。在这个类中有一个名为Question(单数)的枚举,看起来像这样。

public enum Question
{
    Role = 2,
    ProjectFunding = 3,
    TotalEmployee = 4,
    NumberOfServers = 5,
    TopBusinessConcern = 6
}

在Questions类中,我有一个get(intfoo)函数,它为该foo返回Questions对象。有没有一种简单的方法可以从枚举中获取整数值,这样我就可以执行类似于Questions.get(Questions.Role)的操作?


当前回答

Use:

Question question = Question.Role;
int value = question.GetHashCode();

这将导致值==2。

只有当枚举适合于int时,这才是真的。

其他回答

如果您想为存储在变量中的枚举值获取一个整数(其类型为Question),以便在方法中使用,您可以简单地执行我在本例中编写的操作:

enum Talen
{
    Engels = 1, Italiaans = 2, Portugees = 3, Nederlands = 4, Duits = 5, Dens = 6
}

Talen Geselecteerd;    

public void Form1()
{
    InitializeComponent()
    Geselecteerd = Talen.Nederlands;
}

// You can use the Enum type as a parameter, so any enumeration from any enumerator can be used as parameter
void VeranderenTitel(Enum e)
{
    this.Text = Convert.ToInt32(e).ToString();
}

这会将窗口标题更改为4,因为变量Geselecterd是Talen.Nedelands。如果我将其更改为Talen.Portuges并再次调用该方法,文本将更改为3。

你应该使用我们可以在任何其他语言中使用的类型铸造。

如果枚举是这样的-

public enum Question
{
    Role = 2,
    ProjectFunding = 3,
    TotalEmployee = 4,
    NumberOfServers = 5,
    TopBusinessConcern = 6
}

你需要转换为int,然后这样做-

Question q = Question.Role;
.............
.............
int something = (int) q;

Re-

在C#中,有两种类型的铸件:

隐式转换(自动)-将较小的类型转换为较大的类型大小,如-

char->int->long->float->double

显式转换(手动)-将较大的类型转换为较小的类型,如-

double->float->long->int->char

更多信息可以在这里找到。

将其声明为具有公共常量的静态类:

public static class Question
{
    public const int Role = 2;
    public const int ProjectFunding = 3;
    public const int TotalEmployee = 4;
    public const int NumberOfServers = 5;
    public const int TopBusinessConcern = 6;
}

然后,您可以将其引用为Question.Role,它的计算结果始终为int或您定义的任何值。

public enum ViewType
{
    List = 1,
    Table = 2,
};
            
// You can use the Enum type as a parameter, so any enumeration from any enumerator 
// cshtml
// using proyects.Helpers
// @if (Model.ViewType== (int)<variable>.List )

我能想到的最简单的解决方案是重载Get(int)方法,如下所示:

[modifiers] Questions Get(Question q)
{
    return Get((int)q);
}

其中[modifiers]通常可以与Get(int)方法相同。如果无法编辑Questions类或出于某种原因不想编辑,可以通过编写扩展来重载该方法:

public static class Extensions
{
    public static Questions Get(this Questions qs, Question q)
    {
        return qs.Get((int)q);
    }
}