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

前端之家收集整理的这篇文章主要介绍了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或更改你的对象结构.

原文链接:https://www.f2er.com/csharp/100309.html

猜你在找的C#相关文章