我需要读取XML文件并使用LINQ to XML方法。当创建Ignore
类的实例时,会出现问题,因为mode
和pattern
属性不必位于XML中,如果它们应设置为在Ignore
类的构造函数中定义的默认值。LINQ to XML设置的值如果不为零,否则使用构造函数的默认值
下面的代码正常工作,但前提是所有属性都存在于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 ...
}
}
默认值可以随时间变化,我无法在我的加载程序中对它们进行硬编码。
是的,我可以做到这一点。 –