简体   繁体   English

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

[英]How can I refactor these two lines to one statement?

I have the following code: 我有以下代码:

// 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);

The thing I don't like is that I have to create a temp variable, attribute , in order to test if it's null or not, and then assign the value to the BgImage variable, which is a nullable int . 我不喜欢的是我必须创建一个临时变量attribute ,以便测试它是否为null ,然后将值BgImage变量, 变量是一个可以为空的int

I was hoping I could figure out a way to write it all on one line, but I cannot figure a way. 我希望我能找到一种方法将它写在一条线上,但我无法想办法。 I even tried using a ternary statement, but got nowhere: 我甚至尝试使用三元语句,但无处可去:

if (element.TryGetAttributeValue("bgimage") != null) ? BgImage = //Convert result to int :  else null; 

Realistically, my original two lines of code do the job. 实际上,我原来的两行代码完成了这项工作。 I was just hoping to pare it down to one line. 我只是希望把它削减到一条线。 But, if anyone knows how to do what I'm trying to accomplish, I'd love to learn how. 但是,如果有人知道如何做我想要完成的事情,我很乐意学习如何。

I recommend you to use Linq to Xml for parsing Xml (according to your attempt you have BgImage as nullable integer): 我建议您使用Linq to Xml解析Xml(根据您的尝试,您将BgImage作为可以为空的整数):

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

You also can assign some default value if BgImage is not nullable: 如果BgImage不可为空,您还可以指定一些默认值:

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

Assuming TryGetAttributeValue returns a string you could do something like 假设TryGetAttributeValue返回一个string你可以做类似的事情

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

This would set BgImage to a default value ( -1 ) if the attribute does not exist. 如果该属性不存在,这会将BgImage设置为默认值( -1 )。 If you would prefer to have BgImage set to null when there is no bgimage attribute then it gets a little bit clunkier 如果你希望有BgImage设置为null时,有没有bgimage属性,那么它变得有点笨重

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM