c# - LINQ to XML 设置值,如果它不为空,否则使用构造函数的默认值

标签 c# xml linq linq-to-xml

我需要读取一个 XML 文件并且我正在使用 LINQ to XML 方法。创建 Ignore 类的实例时会出现问题,因为 modepattern 属性不必在 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/

相关文章:

c# - Linq 选择项目直到下一次出现

c# - 在 c#.net 中设置饼图中的颜色

c# - 从他们以管理员身份启动的应用程序登录/模拟为本地/域用户

c# - 使用 XElement 从自定义 XML 反序列化 `Dictionary<string, Tuple<string, List<string>>>`

android - 将矢量资源导入 Android Studio 时出错

c# - 从 Web API C# 返回 XML

c# - LINQ 错误无效的初始值设定项成员声明符

c# - 从 Expression<Func<T, T>> 生成动态更新命令

c# - 除非调整窗口大小,否则 WPF 的 Awesomium 不会呈现

c# - 在单个线程上启动第二个消息循环不是有效操作。改为使用 Form.ShowDialog