c# – 当使用泛型类型约束时,XmlSerializer抛出InvalidOperationException

当我尝试运行以下代码(两个分离的程序集)时

ClassLibrary.cs

public interface ITest
{
}

Program.cs中

using System;

public class TestClass
{
    public void Test<T>(T x) where T : ITest { }
}

static class Program
{ 
    static void Main(string[] args)         
    {
        new System.Xml.Serialization.XmlSerializer(typeof(TestClass));
    }
}

使用以下命令在Windows 7 64位中编译:

c:\Windows\Microsoft.NET\Framework\v2.0.50727\csc /target:library ClassLibrary.cs

c:\Windows\Microsoft.NET\Framework\v2.0.50727\csc /reference:ClassLibrary.dll Program.cs

我得到了这个例外:

system.invalidOperationException: Unable to generate a temporary class
(result=1). error CS0012: The type
ITest is defined in an assembly that
is not referenced. You must add a
reference to assembly ClassLibrary,
Version=0.0.0.0,Culture=neutral,
PublicKeyToken=null hinzu.

at
System.Xml.Serialization.Compiler.Compile(Assembly
parent,String ns,
XmlSerializerCompilerParameters
xmlParameters,Evidence evidence)
at
System.Xml.Serialization.TempAssembly.GenerateAssembly(XmlMapping[]
xmlMappings,Type[] types,String
defaultNamespace,Evidence evidence,
XmlSerializerCompilerParameters
parameters,Assembly assembly,
Hashtable assemblies) at
System.Xml.Serialization.TempAssembly..ctor(XmlMapping[]
xmlMappings,String location,
Evidence evidence) at
System.Xml.Serialization.XmlSerializer.GenerateTempAssembly(XmlMapping
xmlMapping,Type type,String
defaultNamespace) at
System.Xml.Serialization.XmlSerializer..ctor(Type
type,String defaultNamespace) at
Program.Main(String[] args)

从TestClass中删除T:ITest或者根本不使用泛型(例如使用public void Test(ITest x))将阻止抛出异常,但我需要在我的实际应用程序中使用此构造.

有人理解为什么XmlSerializer无法处理where约束吗?

解决方法

我认为你是 out of luck.以下是微软对此问题的回应:

Thank you for submitting this issue.
Unfortunately,we have decided that it
will not be addressed because the risk
of the fix outweighs its benefit. By
the time the next opportunity to make
this change comes about,the hope is
that the new serialization
technologies in a future version of
the Windows Communication Foundation
will address your scenario. If this
issue is causing significant negative
business impact,please contact
Microsoft Product Support Services. I
regret that we Could not provide a
better resolution. Rest assured that
we serIoUsly considered this issue – a
Won’t Fix decision is never easy to
make.

这基本上说你应该使用DataContractSerializer而不是XmlSerializer或更改你的对象结构.

相关文章

C#项目进行IIS部署过程中报错及其一般解决方案_c#iis执行语句...
微信扫码登录PC端网站应用的案例(C#)_c# 微信扫码登录
原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...