首页 > 解决方案 > 如何检查xml值的条件?

问题描述

我有两个要在 XML 应用程序中实现的规则。

1 如果重量大于 10,则必须写上名称部门:大

标签: c#xmllinq-to-xml

解决方案


最好让Department属性本身计算其值(计算属性)。当计算发生在您期望的地方时,这更清晰,更易读。否则,在计算取决于多个属性的情况下,您会发现自己在每个参与属性中编写重复的计算代码。
因此,在请求值时执行计算——即Get()调用计算属性时——而不是在参与属性发生更改时。如果计算更复杂,那么遵循此规则也将提高性能。

还要避免直接在属性的Set()/中实现这样的过滤器。Get()将其移至方法。

我还建议使用 switch 语句或 switch 表达式,因为这比长链 if-else 块更具可读性,因此更易于维护。使用 C# 9 时,switch-expression 可以成为一个强大的过滤工​​具,具有可读性强的语法。

此外,由于您尝试为打印输出创建的字符串是string实际Parcel实例的固定表示,因此覆盖Parcel.ToString.

您的 Parcel 类应如下所示:

包裹.cs

public class Parcel
{
  public override string ToString() 
    => $"Name: {this.Name} - Postal code {this.PostalCode} - Weight {this.Weight} - Value {this.Value} - Department {this.Department}";

  public string Name { get; set; }
  public string PostalCode { get; set; }
  public decimal Weight { get; set; }
  public decimal Value { get; set; }
  public string Department => CreateDepartmentValue();

  private string CreateDepartmentValue()
  {
    var result = string.Empty;

    switch (this.Weight)
    {
      case decimal weightInKiloGrams when weightInKiloGrams <= 1: result = "Mail"; break;
      case decimal weightInKiloGrams when weightInKiloGrams <= 10: result = "Regular"; break;
      case decimal weightInKiloGrams when weightInKiloGrams > 10: result = "Heavy"; break;
    };


    switch (this.Value)
    {
      case decimal value when value > 1000: result += ", Insurance"; break;
    };

    return result;
  }
}

使用示例

public class Program
{
  static void Main(string[] args)
  {

    XDocument xdoc = XDocument.Load($"Container.xml");
    var items = ...;

    foreach (var item in items)
    {
      // Call ToString() implicitly
      Console.WriteLine(item);
      Console.WriteLine("*********************************************************************");
    }

    Console.ReadLine();
  }
}

推荐阅读