检查XElement是否全局为null

hs2*_*s2d 5 .net c# xml linq-to-xml

我有一个类,负责读取和保存XML文件.现在它的简单版本看起来像这样:

public class EstEIDPersoConfig
{
    public bool LaunchDebugger { get ; set; }
    public string Password { get; set; }
    public int Slot { get; set; }
    public string Reader { get; set; }
    public string TestInput { get; set; }
    public bool Logging { get; set; }

    public EstEIDPersoConfig()
    {
        XElement xml = XElement.Load(myxml.xml);
        XElement Configuration = xml.Element("Configuration");

        LaunchDebugger = Convert.ToBoolean(Configuration.Element("LaunchDebugger").Value);
        Password = Configuration.Element("Password").Value;
        Slot = Convert.ToInt32(Configuration.Element("Slot").Value);
        Reader = Configuration.Element("Reader").Value;
        TestInput = Configuration.Element("TestInput").Value;
        Logging = Convert.ToBoolean(Configuration.Element("Logging").Value);
     }
 }
Run Code Online (Sandbox Code Playgroud)

之后会有更多.所以问题是如果xml中不存在某些元素我得到System.NullReferenceException.所以我需要检查元素是否null存在.这是一种方法:

var value = Configuration.Element("LaunchDebugger").Value;
if (value != null)
    LaunchDebugger = Convert.ToBoolean(value);
else
    throw new Exception("LaunchDebugger element missing from xml!");
Run Code Online (Sandbox Code Playgroud)

但是为每个元素做这件事太过分了.所以我需要一些好的想法如何简化这个系统,所以它不会在1000行代码中结束.

编辑:编辑了最后一个代码片段,想法是不设置默认值,想法是通知用户xml中缺少此元素是什么.

Jod*_*ell 4

这里的想法直接来自 abatischev 的回答,所以他值得称赞。

正如 Microsoft此处所述,您可以将其转换XElement为您想要的类型。

LaunchDebugger = (bool?)Configuration.Element("LaunchDebugger");
Run Code Online (Sandbox Code Playgroud)

如果你想处理这个null案子我想你可以做

LaunchDebugger = (bool)(Configuration.Element("LaunchDebugger") ?? true);
Run Code Online (Sandbox Code Playgroud)

也许

LaunchDebugger = (bool)(Configuration.Element("LaunchDebugger") ?? false);
Run Code Online (Sandbox Code Playgroud)

取决于你的业务逻辑。如果您对特定类型执行相同的合并场景,则可能适合将这个衬里包装在方法、扩展或其他方式中,但我不确定它会增加很多。