在C#运行时填写/更新枚举值 [英] Fill/update the enum values at runtime in C#

查看:183
本文介绍了在C#运行时填写/更新枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Windows应用程序,我需要在运行时通过读取名为Controls.txt的文本文件填充枚举值。
作为限制,我不认为使用字典。以下是枚举MyControls中可用的默认值。 我只需使用枚举

  public enum MyControls 
{
Button1 = 0,
Button2 = 1,
Button3 = 2,
}

如果Controls.txt文件可用,则枚举的内容应更改为

  public enum MyControls 
{
btn1 = 0,
btn2 = 1,
btn3 = 2,
}

我如何实现这一点?我也碰到了链接在运行时创建/修改枚举,但无法得到想法。

解决方案

我强烈认为您正在尝试解决错误的问题。枚举的值是类型安全。我不认为动态填充是一个好主意。真正有用的是在编译之前使用文本文件(例如)甚至填充枚举。您可以使用VS中的文本模板。



您可以在我的博客文章中找到一个例子: http ://skleanthous.azurewebsites.net/post/2014/05/21/Creating-enums-from-the-database-and-using-them-in-Entity-framework-5-and-later-in-model-first



尽管我的示例从数据库加载,但是将其从文本文件更改为加载应该是微不足道的。


I have windows app where-in i need to fill enum values at runtime by reading a text file named "Controls.txt". As restriction, i'm not suppose to use dictionary. Below is the default values available in the enum MyControls. I have to use enums only.

public enum MyControls
{
   Button1 = 0,
   Button2 = 1,
   Button3 = 2,
}

If Controls.txt file is available, then content of enum should change like

public enum MyControls
{
   btn1 = 0,
   btn2 = 1,
   btn3 = 2,
}

how do i achieve this. I also came across the link Creating / Modifying Enums at Runtime but could not get idea.

解决方案

I strongly think you are trying to solve the wrong problem. The value of enum is type-safety. I do not think that filling it up dynamically is a good idea. What would really be useful is to have an enum populated by a text file (for example) even before compilation. You can do this using text templates in VS.

You can find an example in my blog post here: http://skleanthous.azurewebsites.net/post/2014/05/21/Creating-enums-from-the-database-and-using-them-in-Entity-framework-5-and-later-in-model-first

Although my example loads from a db, changing it to load from a text file should be trivial.

这篇关于在C#运行时填写/更新枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆