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
クラスは不変である必要があるため、最初にデフォルト値でインスタンス化してから、ゲッターのみを提供するプロパティに値を割り当てようとすることはできません。
編集:
誤解された回答に基づいています。クラスは次の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 ...
}
}
デフォルト値は時間の経過とともに変化する可能性があり、ローダーでハードコードすることはできません。