微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/csharp/100309.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐