代表heirarchical枚举

Dev*_*van 8 .net c# enumeration

我有一组枚举值(准确的故障代码).代码是16位无符号整数.我正在寻找一个可以代表这种枚举的数据结构.这里也提出了类似的问题:使用枚举实现层次结构的最佳C#模式是什么?.但这种等级更深层次.


示例枚举值

Current = 0x2000,
Current_DeviceInputSide = 0x2100,
ShortToEarth = 0x2120,
ShortToEarthInPhase1 = 0x2121,
ShortToEarthInPhase2 = 0x2122,
ShortToEarthInPhase3 = 0x2123
Run Code Online (Sandbox Code Playgroud)


用例
当用户提供代码时,UI必须显示具有层次结构的代码的等效含义.
例如,如果用户提供值,0x2121则必须显示UI Short to earth in phase 1 in the current at device input side.表示这一点的最好方法是使用分层表示法:Current : DeviceInputSide : ShortToEarth : ShortToEarthInPhase1.


竞争方法
我有三种竞争方法来表示枚举:

  1. 在层次结构的每个级别创建枚举.然后使用控制器类来解析名称.
  2. 将枚举值存储在xml中,并使用LINQ生成代码的含义.
  3. 将枚举值存储在xml中.在应用程序启动期间.创建单例实例以检索含义.该实例包含一个填充了xml值的字典.


方法1
枚举:

enum WarnCodes
{
    None= 0x000,
    Current = 0x2000
}

enum WarnCodes_Current
{
    DeviceInputSide = 0x2100,
    DeviceOutputSide = 0x2200
}

enum WarnCodes_Current_DeviceInputSide
{
    ShortToEarth = 0x2120,
    ShortCircuit = 0x2130
}

enum WarnCodes_Current_DeviceInputSide_ShortToEarth 
{
    InPhase1 = 0x2121,
    InPhase2 = 0x2122
}
Run Code Online (Sandbox Code Playgroud)

控制器:

public string GetMeaning(int code)
{
    int bitMask = 0xF000;
    int maskedCode = bitMask & code;
    StringBuilder meaning = new StringBuilder();

    switch (maskedCode)
    {
        case WarnCodes.Current:
            meaning.Append("Current : ");
            bitMask = 0xFF00;
            maskedCode = bitMask & code;
            switch (maskedCode)
            {
                case WarnCodes_Current.DeviceInputSide:
                    meaning.Append("Current : Device Input Side :");
                    ...
                    break;
            }

            break;

            ...
    }
}
Run Code Online (Sandbox Code Playgroud)


方法2
存储枚举值的xml如下所示

<WarnCodes>
  <code hex="2000" meaning="Current">
    <code hex="2100" meaning="Current, Device Input side">
      <code hex="2120" meaning="Short to Earth">
        <code hex="2121" meaning="Short to earth in Phase L1"/>
        <code hex="2122" meaning="Short to earth in Phase L2"/>
      </code>
    </code>
  </code>
</WarnCodes>
用于查询代码的方法是:

XElement rootElement = XElement.Load(settingsFilePath);
public string GetHierarchicalMeaning(int code)
{
    XElement rootElement = XElement.Load(warnCodesFilePath);

    List<string> meanings = new List();
    StringBuilder stringBuilder = new StringBuilder();
    IEnumerable<XElement> elements;

    elements = from el in rootElement.Descendants("code")
               where (string)el.Attribute("hex") == code.ToString("X")
               select el;

    XElement element = elements.First();

    while (element.Parent != null)
    {
        meanings.Add(element.Attribute("meaning").Value);
        element = element.Parent;
    }

    meanings.Reverse();

    foreach (string meaning in meanings)
    {
        stringBuilder.AppendFormat("{0} : ", meaning);
    }

    return stringBuilder.ToString().Trim().TrimEnd(':').Trim();
}
Run Code Online (Sandbox Code Playgroud)


方法3
存储枚举值的xml与方法2中的相同.字典是由xmlby 填充的GetChildren().

private Dictionary<int, WarnCodeValue> warnCodesDictionary;

public void Initialize()
{
    XElement rootElement = XElement.Load(settingsFilePath);
    warnCodesDictionary = GetChildren(rootElement);
}

private Dictionary<int, WarnCodeValue> GetChildren(XElement element)
{
    if (element.Descendants().Count() > 0)
    {
        Dictionary<int, WarnCodeValue> childNodeDictionary = new Dictionary();

        foreach (XElement childElement in element.Elements())
        {
            int hex = Convert.ToInt32(childElement.Attribute("hex").Value, 16);
            string meaning = childElement.Attribute("meaning").Value;

            Dictionary<int, WarnCodeValue> dictionary = GetChildren(childElement);
            WarnCodeValue warnCodeValue;
            if (dictionary == null)
            {
                warnCodeValue = new WarnCodeValue() {Meaning = meaning};
            }
            else
            {
                warnCodeValue = new WarnCodeValue() {Meaning = meaning, ChildNodes = dictionary};
            }

            childNodeDictionary.Add(hex, warnCodeValue);
        }

        return childNodeDictionary;
    }

    return null;
}
Run Code Online (Sandbox Code Playgroud)

使用GetHierarchicalMeaning()以下内容检索含义:

public string GetHierarchicalMeaning(int code)
{
    StringBuilder stringBuilder = new StringBuilder();

    int firstLevel = code & 0xF000;
    int secondLevel = code & 0xFF00;
    int thirdLevel = code & 0xFFF0;

    if(warnCodesDictionary.ContainsKey(firstLevel))
    {
        stringBuilder.AppendFormat("{0} : ", warnCodesDictionary[firstLevel].Meaning);
        if (warnCodesDictionary[firstLevel].ChildNodes != null && 
            warnCodesDictionary[firstLevel].ChildNodes.ContainsKey(secondLevel))
        {
            stringBuilder.AppendFormat("{0} : ", warnCodesDictionary[firstLevel].ChildNodes[secondLevel].Meaning);

            if (warnCodesDictionary[firstLevel].ChildNodes[secondLevel].ChildNodes != null &&
                warnCodesDictionary[firstLevel].ChildNodes[secondLevel].ChildNodes.ContainsKey(thirdLevel))
            {
                stringBuilder.AppendFormat("{0} : ", 
                    warnCodesDictionary[firstLevel].ChildNodes[secondLevel].ChildNodes[thirdLevel].Meaning);

                if (warnCodesDictionary[firstLevel].ChildNodes[secondLevel].ChildNodes[thirdLevel].ChildNodes != null &&
                    warnCodesDictionary[firstLevel].ChildNodes[secondLevel].ChildNodes[thirdLevel].ChildNodes.ContainsKey(code))
                {
                    stringBuilder.AppendFormat("{0} : ", 
                        warnCodesDictionary[firstLevel].ChildNodes[secondLevel].ChildNodes[thirdLevel].ChildNodes[code].Meaning);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

WarnCodeValue类:

class WarnCodeValue
{
    public string Meaning
    { get; set; }

    public Dictionary<int, WarnCodeValue> ChildNodes { get; set; }
}
Run Code Online (Sandbox Code Playgroud)


问题

  1. 从性能的角度来看,上述哪三种方法更好?
  2. 是否还有其他方法来表示枚举?
  3. 对代码的任何改进?

Ian*_*ose 5

考虑使用类而不是枚举,然后对每个值使用一个单例,并可以使用类型系统构建树,包括生成错误 txt 等的虚拟方法(这有时可能是一个不错的选择,但也可以引导您进入如果不合适就会有很多问题


Dev*_*van 0

发现方法3的修改版本最合适。感谢@paolo帮助我找到答案。

修改方法3

包含xml代码:

<?xml version="1.0" encoding="utf-8" ?>
<WarnCodes>
  <code hex="2000" meaning="Current">
    <code hex="2100" meaning="Current, Device Input side">
      <code hex="2120" meaning="Short to Earth">
        <code hex="2121" meaning="Short to earth in Phase L1"/>
        <code hex="2122" meaning="Short to earth in Phase L2"/>
      </code>
    </code>
  </code>
  <code hex="3000" meaning="Voltage"/>
</WarnCodes>
Run Code Online (Sandbox Code Playgroud)


班上WarnCodeValue

class WarnCodeValue
{
    public string Meaning
    { get; set; }

    public string ConcatenatedMeaning
    { get; set; }

    public Dictionary<int, WarnCodeValue> ChildNodes 
    { get; set; }
}
Run Code Online (Sandbox Code Playgroud)


处理器singleton类(用于检索代码的含义):

sealed class WarnCodeProcessor
{
    private static Dictionary<int, WarnCodeValue> warnCodesDictionary;

    private static volatile WarnCodeProcessor _instance;

    private static object instanceLockCheck = new object();

    public static WarnCodeProcessor Instance
    {
        get
        {
            lock (instanceLockCheck)
            {
                if (_instance == null)
                {
                    _instance = new WarnCodeProcessor();
                }
            }

            return _instance;
        }
    }

    private WarnCodeProcessor()
    {
        warnCodesDictionary = new Dictionary<int, WarnCodeValue>();

        string currentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        string settingsFilePath = Path.Combine(currentDirectory, "WarnCodes.xml");
        XElement rootElement = XElement.Load(settingsFilePath);

        warnCodesDictionary = GetChildren(rootElement, string.Empty);
    }

    public string GetConcatenatedMeaning(int code)
    {
        string concatenatedMeaning = string.Empty;

        int firstLevel = code & 0xF000;
        int secondLevel = code & 0xFF00;
        int thirdLevel = code & 0xFFF0;

        if (warnCodesDictionary.ContainsKey(firstLevel))
        {
            concatenatedMeaning = warnCodesDictionary[firstLevel].ConcatenatedMeaning;

            if (warnCodesDictionary[firstLevel].ChildNodes != null &&
                warnCodesDictionary[firstLevel].ChildNodes.ContainsKey(secondLevel))
            {
                concatenatedMeaning = 
                    warnCodesDictionary[firstLevel].
                    ChildNodes[secondLevel].ConcatenatedMeaning;

                if (warnCodesDictionary[firstLevel].ChildNodes[secondLevel].ChildNodes != null &&
                    warnCodesDictionary[firstLevel].ChildNodes[secondLevel].ChildNodes.ContainsKey(thirdLevel))
                {
                    concatenatedMeaning = 
                        warnCodesDictionary[firstLevel].
                        ChildNodes[secondLevel].
                        ChildNodes[thirdLevel].ConcatenatedMeaning;

                    if (warnCodesDictionary[firstLevel].ChildNodes[secondLevel].ChildNodes[thirdLevel].ChildNodes != null &&
                        warnCodesDictionary[firstLevel].ChildNodes[secondLevel].ChildNodes[thirdLevel].ChildNodes.ContainsKey(code))
                    {
                        concatenatedMeaning = 
                            warnCodesDictionary[firstLevel].
                            ChildNodes[secondLevel].
                            ChildNodes[thirdLevel].
                            ChildNodes[code].ConcatenatedMeaning;
                    }
                }
            }
        }

        return concatenatedMeaning;
    }

    private static Dictionary<int, WarnCodeValue> GetChildren(XElement element, string concatenatedMeaning)
    {
        string elementMeaning = string.Empty;
        XAttribute attribute = element.Attribute("meaning");
        if (attribute != null)
        {
            elementMeaning = attribute.Value;
            concatenatedMeaning =
                string.IsNullOrEmpty(concatenatedMeaning) ? elementMeaning : string.Format("{0} : {1}", concatenatedMeaning, elementMeaning);
        }

        if (element.Descendants().Count() > 0)
        {
            Dictionary<int, WarnCodeValue> childNodeDictionary = new Dictionary<int, WarnCodeValue>();

            foreach (XElement childElement in element.Elements())
            {
                int hex = Convert.ToInt32(childElement.Attribute("hex").Value, 16);
                string meaning = childElement.Attribute("meaning").Value;

                Dictionary<int, WarnCodeValue> dictionary = GetChildren(childElement, concatenatedMeaning);

                WarnCodeValue warnCodeValue = new WarnCodeValue();
                warnCodeValue.ChildNodes = dictionary;
                warnCodeValue.Meaning = meaning;
                warnCodeValue.ConcatenatedMeaning =
                    string.IsNullOrEmpty(concatenatedMeaning) ? meaning : string.Format("{0} : {1}", concatenatedMeaning, meaning);

                childNodeDictionary.Add(hex, warnCodeValue);
            }

            return childNodeDictionary;
        }

        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)


用法

string concatenatedMeaning = WarnCodeProcessor.Instance.GetConcatenatedMeaning(0x2121);
Run Code Online (Sandbox Code Playgroud)


输出
Current : Current, Device Input side : Short to Earth : Short to earth in Phase L1


可能的修改包括GetMeaning(code)检索代码的原始含义,而不是串联的含义。