从XML中读取C#枚举类型

3

我目前正在使用C#开发一个涉及枚举的项目。

目前代码如下...

public enum Temp
{
    CAREA = 10,
    CAREB = 20,
    CAREC = 22,
    CARED = 35
}

然而,我想从.txt文件或.xml文件中调用相同的数据(作为枚举类型)。任何一种格式都可以。这是为了避免每次添加另一个枚举条目时都需要重新构建(这经常发生)- 编辑.txt或.xml文件将更加容易。


可能是从文件动态生成具有智能感知支持的枚举的重复问题。 - Kris Vandermotten
2
Closers:这不是重复的问题(OP并没有询问Roslyn),也不是“太宽泛”的问题。 - H H
看起来字典路线对我很有用。非常感谢大家的发帖。 - Andy Spencer
4个回答

3

建议您使用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 

我认为这对我来说会起作用。非常感谢。 - Andy Spencer

2
在C#中,枚举是一组命名的常量。如果您从数据源动态生成不同的值,则这些值将不再是常量。看起来像字典在您的情况下更合适。

1
使用字典代替。
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]);
        }
    }
}

0

你无法这样做。枚举值(CAREACAREB等)必须在编译时可用。

但是,你可以在代码中提供所有的值,并从纯文本或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);

@HenkHolterman 不,他不是。 - helb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接