2013-10-16 47 views
2

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

默认值可以随时间变化,我无法在我的加载程序中对它们进行硬编码。

回答

1

你可以使用这样的

一些反思
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; 
+0

是的,我可以做到这一点。 –

0

通字符串参数你GetEnumValue方法

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>((string)y.Attribute("mode")), 
            pattern: GetEnumValue<IgnorePattern>((string)y.Attribute("style")) 
           )) 
          ) 
         }) 
        .ToList(); 

现在改变这样

private static T GetEnumValue<T>(string attribute) 
{ 
    if(attribute==null) return YOURDEFAULTVALUE; 
    else return (T)Enum.Parse(typeof(T), attribute); 
} 

你的方法希望它会为工作,你

+0

它不适合我。看,我不知道默认值,我不能指定它们。默认值是在Ignore类中定义的,我不是该类的作者。我明白了。 –

相关问题