c# - 如何检查xml值的条件?
问题描述
我有两个要在 XML 应用程序中实现的规则。
1 如果重量大于 10,则必须写上名称部门:大
解决方案
最好让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();
}
}
推荐阅读
- ruby - 谷歌云功能授权
- oracle - 如何在保存的搜索中比较 netsuite 中的两列
- .net - 使用带有 TLS 1.2 的 SmtpClient 将未经身份验证的邮件发送到 Microsoft 365
- python - Groupby 有条件,包括 0 次出现
- swift - FileManager:文件上次打开时间的属性
- android - rust and cargo 1.56 根本不适用于 Android NDK r23(没有 binutils)吗?
- javascript - 反应组件或元素未显示在路由器中
- c - 只有最后一个元素在 C 中正确打印双向链表
- python - 调整 Pandas plot.hist() 以获得更好的表示
- computer-vision - 不同相机视图之间的映射