使用泛型使用抽象类的成员的XML序列化

时间:2011-12-29 16:38:15

标签: c# .net generics attributes xml-serialization

对于使用泛型的成员,我遇到了XML序列化问题。以下是我的基本类结构(我希望使用默认的XML序列化,而不是在每个类中重载IXmlSerializable):

public class MyClassToSerialize
{
    public Problem<int> Problem;
}

public class MyOtherClassToSerialize
{
    public Problem<string> Problem;
}

public abstract class Problem<T>
{
}

public class ProblemImplementationOne<T> : Problem<T>
{
}

public class ProblemImplementationTwo<T> : Problem<T>
{
}

现在这就是我的尝试:

[XmlInclude(typeof(ProblemImplementationOne<T>))]
[XmlInclude(typeof(ProblemImplementationTwo<T>))]
public abstract class Problem<T>
{
}

这不起作用:它在属性中使用的<T>参数上给出了编译错误。以下(显然)不起作用,因为它没有提供足够的序列化信息:

[XmlInclude(typeof(ProblemImplementationOne<>))]
[XmlInclude(typeof(ProblemImplementationTwo<>))]
public abstract class Problem<T>
{
}

这给出了序列化时的错误:“通用类型定义不能用于序列化。只能使用特定的泛型类型。”

有没有人知道这个问题的简单解决方案?

1 个答案:

答案 0 :(得分:3)

这样的东西,取决于您要序列化的对象中Problem属性的实际运行时类型:

[XmlInclude(typeof(ProblemImplementationOne<int>))] 
[XmlInclude(typeof(ProblemImplementationTwo<int>))] 
public class MyClassToSerialize 
{ 
    public Problem<int> Problem; 
} 

[XmlInclude(typeof(ProblemImplementationOne<string>))] 
[XmlInclude(typeof(ProblemImplementationTwo<string>))] 
public class MyOtherClassToSerialize 
{ 
    public Problem<string> Problem; 
} 
相关问题