[英]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.