[英]Dynamically find enum values based on enum name
我有1个enum声明的“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);
我希望其他组合框填充选择品牌的枚举(例如奥迪Enum的奥迪模型)。
我试试这个但看起来并不准确......
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);
如果是嵌套类型,则需要使用"+"
而不是"."
我可以想出很多更好的方法来解决你的任务,但这应该在你选择的情况下工作:
private void comboBox3_SelectedValueChanged(object sender, EventArgs e)
{
string value = comboBox1.Text; //car brand
Type type = Type.GetType("YOUR_NAMESPACE." + value);
var brand_models = Enum.GetNames(type);
foreach (string enumValue in brand_models)
{
string brand_model = enumValue;
MessageBox.Show(brand_model);
}
}
请阅读Type.GetType
文档( 可在此处找到 ),以获得针对特定类层次结构和装配情况的正确解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.