如何在一行上将对象转换为对象的新实例? C#

时间:2014-11-02 00:14:17

标签: c# syntax casting

基本上只想转这个

XmlSerializer serializer = new XmlSerializer(typeof(COMPUTER));

COMPUTER computers = (COMPUTER)serializer.Deserialize(new StringReader(Properties.Resources.computerXML));

分成一行。有可能吗?

1 个答案:

答案 0 :(得分:4)

虽然我不明白你需要在一条丑陋的线上完成这件事......

var computers = new XmlSerializer(typeof(COMPUTER)).Deserialize(new StringReader(Properties.Resources.computerXML));
顺便说一句,你正在泄漏你的StringReader,所以要做到这一点没有,你不能把它放在一行。

var serializer = new XmlSerializer(typeof(COMPUTER));
using (var reader = new StringReader(Properties.Resources.computerXML))
{
    var computers = (COMPUTER)serializer.Deserialize(reader);
    // ...
}