我怎样才能将这两行重构为一个陈述?

时间:2014-02-28 13:43:32

标签: c#

我有以下代码:

// TryGetAttributeValue returns string value or null if attribute not found
var attribute = element.TryGetAttributeValue("bgimage");

// Convert attribute to int if not null
if (attribute != null) BgImage = convert.ToInt32(attribute);

我不喜欢的是我必须创建一个临时变量attribute,以便测试它是否为null,然后将值赋给{{1变量,,这是一个可以为空的

我希望我能找到一种方法将它全部写在一条线上,但我无法想办法。我甚至尝试使用三元语句,但无处可去:

BgImage

实际上,我原来的两行代码完成了这项工作。我只是希望把它削减到一条线。但是,如果有人知道如何做我想要完成的事情,我很乐意学习如何。

2 个答案:

答案 0 :(得分:3)

我建议您使用Linq to Xml来解析Xml(根据您的尝试,您将BgImage作为可以为空的整数):

BgImage = (int?)element.Attribute("bgimage");

如果BgImage不可为空,您也可以指定一些默认值:

BgImage = (int?)element.Attribute("bgimage") ?? 0;

答案 1 :(得分:2)

假设TryGetAttributeValue返回string,您可以执行类似

的操作
BgImage = convert.ToInt32(element.TryGetAttributeValue("bgimage") ?? "-1")

如果该属性不存在,这会将BgImage设置为默认值(-1)。如果您希望在没有BgImage属性时将null设置为bgimage,那么它会获得 little 位clunkier

BgImage = element.TryGetAttributeValue("bgimage") != null ? 
    convert.ToInt32(element.TryGetAttributeValue("bgimage")) : (int?)null;
相关问题