我们如何使用类类型来管理硬编码字符串等不同变量。

问题描述:

我们如何使用类类型来管理不同的变量,如硬编码字符串。

How we are using class type to manage different variables like hard coded strings.

我之前没有发帖,因为我没有太多的你有什么问题。



如果你有一个多次使用的字符串,那么我可能会建议使用私有const字符串,但它不会经常发生在你的代码中。每个字符串都被编译和使用,就像一个常量,所以没有任何东西可以获得。你的应用程序可能在磁盘上占用额外的4位:S



我看起来非常庞大且复杂的xml解析器有超过50个字段。字段名称字符串主要用于可读性。这似乎也不适用于此。





我建议添加一些错误处理。不是Try-Catch,而是正确处理可能的错误:

I didn't post earlier because I don't have much of an issue with what you have.

If you had a string that was used many times, then I might suggest using a private const string, but it doesn't happen often in your code. Each string is compiled and used just like a constant so there is nothing to be gained. Your app might take up an extra 4 bits on disk :S

I have seem very large and complex xml parsers with over 50 fields. Field name strings were used mostly for readability. That doesn't appear to apply here either.


I would suggest adding some error handling. Not Try-Catch but properly handling a possible error:
private int PopulateTree(TreeNodeCollection ParentNodes, string ParentText)
{

    string fileName = @"ProductDependency.xml";
    XDocument xdoc;

    if(!File.Exists(fileName)
       return 10; //error code?

    using (Stream input = File.OpenRead(fileName))
    {
        xdoc = XDocument.Load(input);
    }

    var level1s = from level1 in xdoc.Descendants("ProductType")
        select new
        {
             Header = level1.Attribute("value")==null?"":level1.Attribute("value").Value,
             Children = level1.Descendants("Firmware")
        };

    TreeNode tn = new TreeNode(ParentText.ToString());

    //adding parent node
    ParentNodes.Add(tn);

    int i = 0;

    foreach (var ProductType in level1s)
    {

        //adding child node
        tn.Nodes.Add(new TreeNode(ProductType.Header));



        foreach (var child in ProductType.Children)
        {

            string childId;

            if (child.Attribute("Dependent") != null &&
                Convert.ToString(child.Attribute("Dependent").Value) == "Independent")
            {
                childId = child.Attribute("id").Value;
            }
            else if(child.Attribute("id") != null)
            {
                childId = child.Attribute("id").Value + " (Required " + Convert.ToString(child.Attribute("Dependent").Value) + ")";
            }
            else
                return 20; //error code?

            //adding sub child node
            tn.Nodes[i].Nodes.Add(new TreeNode(childId));

        }

        //go to next child node
        i++;
    }

    // expend all child node only
    if (tn.Level == 0)
        tn.Expand();
}





我刚刚在那里添加了一些想法。它可以避免在文件移动或损坏时遇到异常。



I just added some ideas there. It avoids hitting exceptions in case the file is moved or gets corrupted.