[英]How to pass an value of type enum to another enum variable?
我正在獲取enum變量中的值,但是在將其分配給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將始終為零。
這對我來說很好。 我認為您有一個表格,其中有一個下拉式組合框,其中包含項目。 所以我復制了這些,這里是代碼。 下拉列表中填充的項目(按順序排列)與下面的代碼(枚舉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屬性正確設置為下拉菜單中選擇的項目。
在下拉菜單中選擇“布爾”后,該屬性將設置為“布爾”,如第二幅圖像所示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.