我需要读取一个 XML 文件,并且我正在使用 LINQ to XML 方法。创建Ignore
类的实例时会出现问题,因为mode
如果pattern
应该将属性设置为在类的构造函数中定义的默认值,则它们不必在 XML 中Ignore
。
下面的代码有效,但前提是所有属性都存在于 XML 文件中。
var items = xmlFile.Descendants("item")
.Select(x => new Item()
{
SourcePath = x.Attribute("source").ToString(),
DestinationPath = x.Attribute("destination").ToString(),
IgnoredSubitems = new List<Ignore>(
x.Elements("ignore")
.Select(y => new Ignore(
path: y.Value,
mode: GetEnumValue<IgnoreMode>(y.Attribute("mode")),
pattern: GetEnumValue<IgnorePattern>(y.Attribute("style"))
))
)
})
.ToList();
GetEnumValue
用于设置枚举类型的方法如下所示
private static T GetEnumValue<T>(XAttribute attribute)
{
return (T)Enum.Parse(typeof(T), attribute.ToString());
}
有没有办法只在有值的情况下设置字段,否则使用构造函数中定义的默认值?该类应该是不可变Ignore
的,因此我不能先用默认值实例化它,然后尝试将值分配给仅提供 getter 的属性。
编辑:
基于误解的答案。该类Ignore
如下所示。请注意,这不是我的课。
public class Ignore
{
string Path { get; }
IgnoreMode Mode { get; } // enum
IgnorePattern Pattern { get; } // enum
public Ignore(string path, IgnoreMode mode = someDefaultValue, IgnorePattern pattern = someDefaultPattern)
{
... I don't know what happens here, but I guess that arguments are assigned to the properties ...
}
}
默认值会随着时间而改变,我不能在我的加载器中对它们进行硬编码。