我目前正在使用C#开发一个涉及枚举的项目。
目前代码如下...
public enum Temp
{
CAREA = 10,
CAREB = 20,
CAREC = 22,
CARED = 35
}
然而,我想从.txt文件或.xml文件中调用相同的数据(作为枚举类型)。任何一种格式都可以。这是为了避免每次添加另一个枚举条目时都需要重新构建(这经常发生)- 编辑.txt或.xml文件将更加容易。
我目前正在使用C#开发一个涉及枚举的项目。
目前代码如下...
public enum Temp
{
CAREA = 10,
CAREB = 20,
CAREC = 22,
CARED = 35
}
然而,我想从.txt文件或.xml文件中调用相同的数据(作为枚举类型)。任何一种格式都可以。这是为了避免每次添加另一个枚举条目时都需要重新构建(这经常发生)- 编辑.txt或.xml文件将更加容易。
建议您使用Dictionary,而非在运行时动态更改的枚举。
class MyClass
{
private Dictionary<string, int> tempValues = new Dictionary<string, int>() {
{ "CAREA", 10 },
{ "CAREB", 20 },
{ "CAREC", 22 },
{ "CARED", 35 }
}
public Dictionary<string, int> TempValues
{
get
{
return this.tempValues
}
}
}
您仍需从文件中加载值并填充它们:
private void ReadValues(string path)
{
foreach(string line in File.ReadAllLines(path))
{
string[] tokens = string.Split(',');
string key = tokens[0];
int value = int.Parse(tokens[1]);
// TODO: check if key does not already exist
this.tempValues.Add(key, value);
}
}
CAREA,10
CAREB,20
CAREC,22
CARED,35
var myEnums = new Dictionary<string, int>();
public void ReadIt()
{
// Open your textfile into a streamreader
using (System.IO.StreamReader sr = new System.IO.StreamReader("text_path_here.txt"))
{
while (!sr.EndOfStream) // Keep reading until we get to the end
{
string splitMe = sr.ReadLine(); //suppose key and value are stored like "CAREA:10"
string[] keyValuePair = splitMe.Split(new char[] { ':' }); //Split at the colons
myEnums.Add(keyValuePair[0], (int)keyValuePair[1]);
}
}
}
你无法这样做。枚举值(CAREA
,CAREB
等)必须在编译时可用。
但是,你可以在代码中提供所有的值,并从纯文本或XML文件中解析支持的内容。你可以使用以下扩展方法来实现。
/// <summary>
/// Converts the string to a specified enumeration.
/// A value specifies whether the operation is case-insensitive.
/// </summary>
/// <typeparam name="TEnum">The type of System.Enum to parse as.</typeparam>
/// <param name="value">The System.String value.</param>
/// <param name="ignoreCase"><c>true</c> to ignore case; <c>false</c> to regard case.</param>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException"><paramref name="value"/> does not map to one of the named constants defined in <typeparamref name="TEnum"/>.</exception>
public static TEnum ParseAs<TEnum>(this String value, bool ignoreCase)
where TEnum : struct
{
return (TEnum)Enum.Parse(typeof(TEnum), value, ignoreCase);
}
使用方法:
var enumValue = "CAREA".ParseAs<Temp>(ignoreCase: false);