2

如果函数体中发生异常,如何返回新的空类型 T?

如果在反序列化 xml 时出现问题,将 x 转换为新 T() 的最佳方法是什么?

看看我是如何得到 catch 块的,我将如何处理这个?

        public static T DeserializeXml<T>(this string xml) where T : class
    {

        XmlDocument doc = new XmlDocument();
        MemoryStream ms = new MemoryStream();
        StreamReader sr = null;
        T x = null;
        //
        try
        {
            doc.LoadXml(xml); doc.Save(ms);
            ms.Position = 0;
            sr = new StreamReader(ms);
            XmlSerializer i = new XmlSerializer(typeof(T));
            x = (T)i.Deserialize(sr);
        }
        catch (Exception) {
            x = null;
        }
        finally {
        sr.Close(); sr.Dispose(); ms.Close(); ms.Dispose();
        }
        //
        return x as T;
    }
4

4 回答 4

3

你可以使用默认值

return default(T);
于 2012-10-25T05:18:45.483 回答
3

您可以约束T拥有一个空的构造函数。你问的是这个吗?

public static T DeserializeXml<T>(this string xml) where T : class, new()
{
    //...
    catch
    {
        x = new T();
    }
    //...
    return x as T;       
}
于 2012-10-25T05:18:55.967 回答
2

你真正需要做的就是

catch (Exception) {
    x = default(T);
}

或类似的东西。真的,你可以只return nullcatch子句中;除非您拔下电源插头,否则该finally子句仍保证运行,并且where T: class约束确保 default(T) 始终为空。

考虑使用一些using块,而不是那些关闭和处置。然后你根本不需要一个finally块。

public static T DeserializeXml<T>(this string xml) where T : class
{

    XmlDocument doc = new XmlDocument();
    using (MemoryStream ms = new MemoryStream())
    {
        using (StreamReader sr = new XmlSerializer(typeof(T))
        {
            T x = null;

            try
            {
                doc.LoadXml(xml); doc.Save(ms);
                ms.Position = 0;
                sr = new StreamReader(ms);
                XmlSerializer i = new XmlSerializer(typeof(T));
                x = (T)i.Deserialize(sr);
            }
            catch (Exception) {
                return null;
            }
        }
    }
    return x;
}
于 2012-10-25T05:18:57.290 回答
2

您可以返回default(T),也可以向泛型类型添加约束where T : new(),在这种情况下,您可以返回new T()

基本上,default(T)适用于您不知道T是值类型还是引用类型的情况。它为不同的类型返回不同的东西——类的 null ,数字类型的零和结构的空实例。MSDN 上有一篇很好的文章。

于 2012-10-25T05:19:02.120 回答