C# 如何组合使用和try/catch语句?
以下是我的方法:C# 如何组合使用和try/catch语句?,c#,C#,以下是我的方法: public BackgroundJobInfo Deserialize(string info) { using (var stringReader = new StringReader(info)) { try { var xmlTextReader = XmlReader.Create(stringReader); return (BackgroundJobInfo)Seria
public BackgroundJobInfo Deserialize(string info)
{
using (var stringReader = new StringReader(info))
{
try
{
var xmlTextReader = XmlReader.Create(stringReader);
return (BackgroundJobInfo)Serializer.ReadObject(xmlTextReader);
}
catch (Exception e)
{
_logger.ErrorException(e, "Error when deserializing a BackgroundJobInfo object from string <{0}>", info);
return null;
}
}
}
publicbackgroundjobinfo反序列化(字符串信息)
{
使用(var stringReader=newstringreader(info))
{
尝试
{
var xmlTextReader=XmlReader.Create(stringReader);
return(BackgroundJobInfo)Serializer.ReadObject(xmlTextReader);
}
捕获(例外e)
{
_ErrorException(e,“从字符串反序列化BackgroundJobInfo对象时出错”,info);
返回null;
}
}
}
我需要在哪里使用
using()
语句?可能就在try{…}
?内,因为try块外不需要stringReader,我建议您这样使用它:
public BackgroundJobInfo Deserialize(string info)
{
try
{
using (var stringReader = new StringReader(info))
{
var xmlTextReader = XmlReader.Create(stringReader);
return (BackgroundJobInfo)Serializer.ReadObject(xmlTextReader);
}
}
catch (Exception e)
{
_logger.ErrorException(e, "Error when deserializing a BackgroundJobInfo object from string <{0}>", info);
return null;
}
}
publicbackgroundjobinfo反序列化(字符串信息)
{
尝试
{
使用(var stringReader=newstringreader(info))
{
var xmlTextReader=XmlReader.Create(stringReader);
return(BackgroundJobInfo)Serializer.ReadObject(xmlTextReader);
}
}
捕获(例外e)
{
_ErrorException(e,“从字符串反序列化BackgroundJobInfo对象时出错”,info);
返回null;
}
}
但最后,你要决定如何使用它。解释一下你希望这个方法做什么
new StringReader()
可以抛出,但您的try-catch无法捕获。什么不起作用?一切正常。但是使用试捕和使用的常见做法是什么?有什么建议吗?那就没什么区别了?