Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将这两行重构为一条语句?_C# - Fatal编程技术网

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;