Skip to main content
 首页 » 编程设计

c#之根据枚举名称动态查找枚举值

2024年02月13日14cloudgamer

我有 1 个这样的“car_brands”枚举声明:

public enum Car_brands 
{ 
    Audi = 1, 
    ... 
    ... 
} 

和许多其他枚举每个“car_brand”的声明

public enum Audi 
{ 
    model_a3 = 1, 
    model_a4 = 2, 
    ... 
} 

我关联了 2 个组合框。一个与 car_brands 相关联:

 comboBox1.DataSource = new BindingSource(Car_brands.Keys, null); 

我希望其他组合框填充选定品牌的枚举(例如奥迪的奥迪枚举模型)。

我试过了,但似乎不准确...

private void comboBox3_SelectedValueChanged(object sender, EventArgs e) 
        { 
string value = comboBox1.Text;   //car brand 
Type type = Type.GetType(value); 
var brand_models = Enum.GetNames(type.GetType()); 
                foreach (string enumValue in brand_models) 
                    { 
                        string brand_model = enumValue; 
                        MessageBox.Show(brand_model); 
                    } 
 
        } 

请您参考如下方法:

Type type = Type.GetType("full namespace where you declare enum" + "." + value); 
var brand_models = Enum.GetNames(type); 

在嵌套类型的情况下,您需要使用 "+" 而不是 "."

C# : having a "+" in the class name?