方法返回类型 list<string> 还是泛型方法?

Mit*_*nca -4 c# xml generics

我希望该方法具有特定的返回类型,但不知何故我无法使其工作。

我有一个 XML 结构:

<Notifications>
   <Alerts>
      <Max>3<Max/>
      <Med>2<Med/>
      <Min>1<Min/>
   </Alerts>
</Notifications>
Run Code Online (Sandbox Code Playgroud)

我想得到Max, Med,的值Min。但要点是我根本不需要任何 foreach 循环,我只希望该方法具有 List<string> 返回类型,或者更好地创建通用返回类型。

关键是,我没有任何自定义类(而且我不想拥有它)来填充其属性。

这是我到目前为止所知道的,但我在“List()”匿名方法上遇到了错误:

Here it returns:
List<string> items = GetAlerts();

//method to read:
public List<string> GetAlerts()
{
    return xmlDoc1.Descendants("Notifications").Elements("Alerts").Select(s => new
    {
        MAX = s.Element("Max").Value,
        MED = s.Element("Med").Value,
        MIN = s.Element("Min").Value
     }).ToList(); //error on this line
}
Run Code Online (Sandbox Code Playgroud)

----------


如果这个方法是一个泛型返回类型,看起来会怎么样?这是不行的:

Here it returns: 
List<object> items = setBLL2.GetAlert<List<object>>();

public T GetAlert<T>() where T:class
{
    return (T)xmlDoc1.Descendants("Notifications").Elements("Alerts").Select(s => new
    //ERROR up here before (T
    {
         MAX = s.Element("Max").Value,
         MED = s.Element("Med").Value,
         MIN = s.Element("Min").Value
     }).ToList();
}
Run Code Online (Sandbox Code Playgroud)

错误信息是:

无法将类型“System.Collections.Generic.List”转换为“T”

Dou*_*las 5

List<T>您不能跨方法边界传输匿名类型(在您的情况下,作为从您的方法返回的泛型类型)。

您应该使用MaxMedMin作为属性定义一个类或结构,并通过您的方法初始化其实例的列表。

public class Alert
{
    public string Max { get; set; }
    public string Med { get; set; }
    public string Min { get; set; }
}

public IList<Alert> GetAlerts()
{
    return (xmlDoc1.Descendant("Notifications").Elements("Alerts").Select(s => 
        new Alert
        {
            Max = s.Element("Max").Value,
            Med = s.Element("Med").Value,
            Min = s.Element("Min").Value
        }).ToList();
}
Run Code Online (Sandbox Code Playgroud)

编辑:作为替代方案,您可以返回将属性名称映射到其值的字典列表:

public IList<Dictionary<string,string>> GetAlerts()
{
    return (xmlDoc1.Descendant("Notifications").Elements("Alerts").Select(s => 
        new Dictionary<string,string>
        {
            { "Max", s.Element("Max").Value },
            { "Med", s.Element("Med").Value },
            { "Min", s.Element("Min").Value }
        }).ToList();
}
Run Code Online (Sandbox Code Playgroud)

您可以使用以下代码访问您的值:

string firstMin = alerts[0]["Min"];
Run Code Online (Sandbox Code Playgroud)

  • @MitjaBonca所以你以正确的方式做了,但你想学习,所以你问如何以错误的方式做?如果您想将您的方法与解决同一问题的其他可能方法进行比较,或者让人们对您进行代码审查,那么请访问programmers.stackexchange,看看哪种方法更好。不要提出限制用户提供解决问题的最佳方法的问题。 (2认同)