C# 如何将enum类型的值传递给另一个enum变量?

C# 如何将enum类型的值传递给另一个enum变量?,c#,C#,我在一个枚举变量中获取的值,但在将其分配给另一个类型为enum的变量时,它始终获取0…下面是我使用的代码,dbProperties是dbProperties类的对象,该类具有DBType类型的成员。dbProperties.DBType始终返回0,即使在为其赋值后也是如此…请帮助 DBType val = (DBType)cbDataType.SelectedIndex; cbDataType.SelectedIndex = (int)val; dbProperties.DBType = val

我在一个枚举变量中获取的值,但在将其分配给另一个类型为enum的变量时,它始终获取0…下面是我使用的代码,dbProperties是dbProperties类的对象,该类具有DBType类型的成员。dbProperties.DBType始终返回0,即使在为其赋值后也是如此…请帮助

DBType val = (DBType)cbDataType.SelectedIndex;
cbDataType.SelectedIndex = (int)val;
dbProperties.DBType = val;

那么dbProperties.DBType是DBType类型的变量的名称

不确定为什么它总是返回0,但我认为这与为枚举赋值无关

运行以下代码,例如:

enum DBType
{
    Int,
    Bool,
    String
}

class DBProperties
{
    public DBType DBType;
}

class Program
{
    static void Main(string[] args)
    {
        DBType d = (DBType)2;
        DBProperties p = new DBProperties();
        p.DBType = d;
        Console.WriteLine((int)p.DBType); //outputs 2
        Console.ReadLine();
    }
}

你需要更清楚、更具体地回答你的问题,这样人们才能帮助你


您确定
val
不总是零吗?如果您总是在下拉框中选择第一个选项,则selectedIndex将始终为零。

这对我来说很好。我想你有一个表单,其中有一个下拉组合框,里面有项目。所以我复制了它,下面是代码。下拉列表中填充的项目与下面的代码(enum DBType)中显示的项目以及所附的第一个图像中显示的项目相匹配(按顺序排列)

  enum DBType { Int, Double, Float, Bool, String  }

  class DBProperties
  {
    private DBType dbType;
    public DBType DBType { get { return dbType; } set { dbType = value; } }
  }

  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void cbDataType_SelectedIndexChanged(object sender, EventArgs e)
    {
      DBType val = (DBType)cbDataType.SelectedIndex;
      cbDataType.SelectedIndex = (int)val;
      var dbProperties = new DBProperties();
      dbProperties.DBType = val;
    }
  }
dbProperties.DBType属性已正确设置为下拉列表中选定的项。


在下拉列表中选择“bool”时,属性设置为“bool”,如第二幅图所示。

@Chris,这实际上不是解释枚举的方法,因为您分配的值为2,而不是任何emun元素的值。对于枚举中的两个元素,值(除非另有规定)为0和1。C#允许您(错误地)将值分配到第个枚举的边界之外(遗憾的是)。如果将第一个变量赋给1,然后在调用eConsole.Writeline()时删除对int的强制转换,您将看到它输出“Bool”而不是“2”。是的,我知道,我只是创建了一个更完整的代码版本,以证明它不会输出DBProperties类中使用的0.Constructor。私有DBType DBType=new DBType();公共DBType DBType{get{return DBType;}set{DBType=DBType;}}}我试过那段代码,但仍然不起作用……我的DBProperties类有什么问题吗?@user654748请在原始问题中显示实际的类定义。您在这里粘贴的是无效的C代码。@user654748,我已修改了我的答案,以包含不使用自动属性get的DBProperties类定义;设置前两行代码的意义是什么?为什么不直接执行
dbProperties.DBType=(DBType)cbDataType.SelectedIndex
?此外,我建议将活动枚举值放在组合框中,并通过
SelectedItem