为什么我不能在 C# 中序列化元组?

Why I could not serialize a tuple in C#?(为什么我不能在 C# 中序列化元组?)

本文介绍了为什么我不能在 C# 中序列化元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
为什么 XML-Serializable 类需要无参数构造函数

我正在尝试在我的代码中序列化一个元组:

I'm trying to serialize a tuple in my code:

List<List<Tuple<String, CodeExtractor.StatementNode>>> results = null;
results = extractor.ExtractSourceCode(sourceCode);
FileStream fs = new FileStream(@"C:ProjectsTestast.xml", FileMode.Create);

XmlSerializer formatter = new XmlSerializer(
    typeof(List<List<Tuple<String, CodeExtractor.StatementNode>>>));

formatter.Serialize(fs, results);

fs.Close();

但它失败了并像这样捕获异常:

but it was failed and catch the exception like this:

System.Tuple`2[System.String,CodeExtractor.StatementNode] 无法序列化,因为它没有无参数构造函数.

System.Tuple`2[System.String,CodeExtractor.StatementNode] cannot be serialized because it does not have a parameterless constructor.

我确信 CodeExtractor.StatementNode 可以被序列化.

and I'm do sure the CodeExtractor.StatementNode could be serialized.

推荐答案

为了 XmlSerializer 能够完成它的工作,它需要一个默认的构造函数.那是一个不带参数的构造函数.所有 Tuple<...> 类都有一个构造函数,并且该构造函数接受多个参数.元组中的每个值一个.所以在你的情况下,唯一的构造函数是

For XmlSerializer to be able to do its job it needs a default contructor. That is a constructor that takes no arguments. All the Tuple<...> classes have a single constructor and that constructor takes a number of arguments. One for each value in the tuple. So in your case the sole constructor is

Tuple(T1 value1, T2 value2)

序列化程序正在寻找一个不带参数的构造函数,但因为找不到它,所以你得到了异常.

The serializer is looking for a constructor with no arguments and because it can't find it, you get the exception.

你可以创建一个可变类,它可以代替元组来进行序列化

you could create a mutable class, that could be substituted for tuples for the purpose of serialization

class MyTuple<T1, T2>
{
    MyTuple() { }

    public T1 Item1 { get; set; }
    public T2 Item2 { get; set; }

    public static implicit operator MyTuple<T1, T2>(Tuple<T1, T2> t)
    {
         return new MyTuple<T1, T2>(){
                      Item1 = t.Item1,
                      Item2 = t.Item2
                    };
    }

    public static implicit operator Tuple<T1, T2>(MyTuple<T1, T2> t)
    {
        return Tuple.Create(t.Item1, t.Item2);
    }
}

你可以通过以下方式使用它

You could then use it the following way

XmlSerializer formatter = new XmlSerializer(
    typeof(List<List<MyTuple<String, CodeExtractor.StatementNode>>>));

formatter.Serialize(fs, results.SelectMany(
                              lst => lst.Select(
                                        t => (MyTuple)t
                                     ).ToList()
                              ).ToList());

这篇关于为什么我不能在 C# 中序列化元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么我不能在 C# 中序列化元组?

基础教程推荐