无法从'System.Collections.Generic.List转换 'to'System.Xml.Linq.XName'

问题描述 投票:-1回答:1

我收到编译器错误:'System.Collections.Generic.List'到'System.Xml.Linq.XName'。

我原来得到的'XAttribute'不包含'Trim'的定义,也没有可访问的扩展方法'Trim'......等等。但我想我发现我的报价出错了地方。

我究竟做错了什么?

    public static List<Phrase> LoadPhrasesFromXMLFile(string file)
    {
        try
        {
            XDocument xdocument = XDocument.Load(file);
            char[] trim = new char[3] { '\'', '"', ' ' };
            return xdocument.Descendants("Phrase").Select((Func<XElement, Phrase>)(x => new Phrase()
            {
                eventname = (string)x.Attribute("Event".Trim(trim)),
                priority = int.Parse((string)x.Attribute("Priority".Trim(trim))),
                words = x.Descendants("Word").Select((Func<XElement, Word>)(y =>
                {
                    Word word1 = new Word
                    {
                        preferred_text = (string)y.Attribute("Primaries".Trim(trim).ToLower())
                    };
                    List<string> stringList = (string)y.Attribute("Secondaries") == null || string.IsNullOrWhiteSpace((string)y.Attribute("Secondaries"))
                        ? new List<string>()

在这一行失败:

                        : (List<string>)(IEnumerable<string>)(string)y.Attribute("Secondaries".Trim(trim).Replace(" ", "").ToLower().Split(',').ToList());

续码:

                    Word word2 = word1;
                    word2.Ssecondaries = stringList;
                    return word1;
                })).ToList<Word>()
            })).ToList<Phrase>();
        }

错误捕获:

        catch (Exception ex)
        {
            Sup.Logger("Encountered an exception reading '" + file + "'. It was: " + ex.ToString(), false, true);
        }
        return (List<Phrase>)null;
    }
c# string xname
1个回答
0
投票

欢迎来到StackOverflow!

首先,考虑清理一些一般风格的第一条评论。代码很难阅读以及具有多个分割代码块的问题。

有问题的行的语法错误通过将其更改为以下来解决(有

    y.Attribute("Secondaries").Value.Trim(trim).Replace(" ", "").ToLower().Split(',').ToList())

您不需要进行任何转换,因为ToList()已经使它成为List。这是确切的编译器问题的结束。

在如何制作更干净的代码方面,考虑制作辅助函数:

    // move 'trim' into an accessible memory location
    private string SanitizeInput (string input) 
    { 
        return input.Trim(trim).Replace(" ", "").ToLower();
    }

    // Having a function like this will change your solution code from the line above to:
    SanitizeInput(y.Attributes("Secondaries).Value).Split(',').ToList();
    // This line is much easier to read as you can tell that the XML parsing is happening, being cleaned, and then manipulated.

另一件需要考虑的事情,Word.Ssecondaries(看起来你的参数名称可能有拼写错误?)是要查看该属性是否可以设置为IEnumerable。将它存储为List是危险的,因为任何代码都可能更改Word.Secondaries。如果您不打算更改它,IEnumerable会更安全。如果您发现IEnumerable满足您的需求,您可以删除有问题的行中的.ToList(),避免为列表分配新的内存块,以及使用来自LINQ的延迟评估查询的代码更快

© www.soinside.com 2019 - 2024. All rights reserved.