有没有办法删除try-catch和使用if ???
进行相同的工作 try
{
StorageFile sessionFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(GUID, CreationCollisionOption.OpenIfExists);
if (sessionFile == null)
return Guid.Empty;
using (IInputStream sessionInputStream = await sessionFile.OpenReadAsync())
{
var sessionSerializer = new DataContractSerializer(typeof(Guid));
return (Guid)sessionSerializer.ReadObject(sessionInputStream.AsStreamForRead());
}
}
catch (System.Xml.XmlException e)
{
return Guid.Empty;
}
如果文件不是XML格式,或者??
,我认为我得到了Exception答案 0 :(得分:1)
不,基本上。没有TryReadObject
方法,大多数序列化程序都不具备这种方法。您当然可以添加 TryReadObject
扩展名方法,即
public static T TryReadObject<T>(this IInputStream sessionInputStream, out T value)
{
try
{
var serializer = new DataContractSerializer(typeof(T));
using(var stream = sessionInputStream.AsStreamForRead())
{
value = (T)serializer.ReadObject(stream);
return true;
}
}
catch
{
value = default(T);
return false;
}
}
但这只会移动异常处理。但是你可以使用:
StorageFile sessionFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(GUID, CreationCollisionOption.OpenIfExists);
if (sessionFile == null)
return Guid.Empty;
using (IInputStream sessionInputStream = await sessionFile.OpenReadAsync())
{
Guid val;
return sessionInputStream.TryReadObject<Guid>(out val) ? val : Guid.Empty;
}