我需要读取一个 XML 文件并且我正在使用 LINQ to XML 方法。创建 Ignore
类的实例时会出现问题,因为 mode
和 pattern
属性不必在 XML 中(如果它们应该在 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 ...
}
}
默认值会随着时间的推移而改变,我不能在我的加载程序中对它们进行硬编码。
最佳答案
你可以像这样使用一些反射
var constructor = typeof(Ignore).GetConstructor(new Type[]{typeof(string),typeof(IgnoreMode),typeof(IgnorePattern)});
var parameters = constructor.GetParameters(); // this return list parameters of selected constructor
var defaultIgnoreMode = (IgnoreMode)parameters[1].DefaultValue;
var defaultIgnorePattern = (IgnorePattern)parameters[2].DefaultValue;
关于c# - LINQ to XML 设置值,如果它不为空,否则使用构造函数的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19398813/