C# 如何将这两行重构为一条语句?
我有以下代码:C# 如何将这两行重构为一条语句?,c#,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); 我不喜欢的是
// 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
,然后将该值赋给BgImage
变量,它是一个可为null的int
我希望我能想出一个办法把它写在一行上,但我想不出一个办法。我甚至尝试过使用三元语句,但没有成功:
if (element.TryGetAttributeValue("bgimage") != null) ? BgImage = //Convert result to int : else null;
实际上,我原来的两行代码就可以完成这项工作。我只是希望把它缩减到一行。但是,如果有人知道如何完成我要完成的任务,我很乐意学习如何完成。我建议您使用解析Xml(根据您的尝试,您将BgImage设置为可空整数):
如果BgImage不可为空,您还可以指定一些默认值:
BgImage = (int?)element.Attribute("bgimage") ?? 0;
假设
TryGetAttributeValue
返回一个字符串
,您可以执行以下操作
BgImage = convert.ToInt32(element.TryGetAttributeValue("bgimage") ?? "-1")
如果属性不存在,这会将BgImage
设置为默认值(-1
)。如果您希望在没有BgImage
属性时将BgImage
设置为null
,那么它会变得有点笨重
BgImage = element.TryGetAttributeValue("bgimage") != null ?
convert.ToInt32(element.TryGetAttributeValue("bgimage")) : (int?)null;
你在解析xml之类的东西吗?一个
TryGetAttributeValueAsInt
扩展名?@SergeyBerezovskiy是的,我是。BgImage属性可以是null,也可以是int,包括零。@KevinJ如果属性不存在,您希望有什么值?@AlexK。实际上,我考虑过这样做,但在编写另一个扩展方法之前,我想看看我所尝试的是否可行。他说,如果我找不到答案,我可能会这样做。我假设BgImage
如果属性为null,则应该为null而不是-1。TryGetAttributeValue
如果找到,则返回一个字符串;如果未找到,则返回null
。BgColor可以是一个int,包括零,也可以是一个null
值。@KevinJ所以在找不到属性的情况下,您最好将BgImage
设置为null
?@James这是正确的。我正在解析的XML可以有“bgcolor=“0”
或“bgcolor”=其他一些int
或根本没有“bgcolor”
属性。这对我来说很好。我根本不必使用“TryGetAttribute”方法,我得到了我想要的结果。我会在计时器启动后将此标记为答案。谢谢!
BgImage = element.TryGetAttributeValue("bgimage") != null ?
convert.ToInt32(element.TryGetAttributeValue("bgimage")) : (int?)null;