序列化XML,删除try-catch insert而不是if

本文关键字:if insert try-catch XML 删除 序列化 | 更新日期: 2023-09-27 18:22:08

是否有任何方法可以删除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格式的,或者??

序列化XML,删除try-catch insert而不是if

基本上没有。没有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;
}