1

有什么方法可以删除 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 格式,我想我会得到异常,或者?

4

1 回答 1

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;
}
于 2013-07-12T09:27:34.103 回答