我开发(重写到 WCF)一个接受 string[]
并返回 ISection[]
的文件解析 Web 服务,但实际上这是一组嵌套接口(interface):
namespace Project.Contracts // Project.Contracts.dll
{
public interface ISection { }
public interface ISummarySection : ISection { }
public interface IDataSection : ISection { }
}
和类:
namespace Project.Format.A // Project.Format.A.dll
{
[DataContract]
public class SummarySectionFormatA : ISummarySection { }
[DataContract]
public class DataSectionFormatA : IDataSection { }
}
服务接口(interface)及其实现:
[ServiceContract]
public interface IService // Project.Contracts.dll
{
ISection[] Parse(string format, string[] data);
}
[ServiceKnownType(typeof(SummarySectionFormatA))] // tried this also
[ServiceKnownType(typeof(DataSectionFormatA))]
public class Service : IService // Project.Service.dll
{
public ISection[] Parse(string format, string[] data)
{
return Factory.Create(format).Parse(data);
}
}
我尝试在服务器和客户端上配置 declaredTypes
:
<system.runtime.serialization>
<dataContractSerializer>
<declaredTypes>
<add type="Project.Contracts.ISumarySection, Project.Contracts">
<knownType type="Project.Format.A.SummarySectionFormatA, Project.Format.A" />
</add>
<add type="Project.Contracts.IDataSection, Project.Contracts">
<knownType type="Project.Format.A.DataSectionFormatA, Project.Format.A" />
</add>
</declaredTypes>
</dataContractSerializer>
</system.runtime.serialization>
但还是报同样的错误:
"Type 'DataSectionFormatA' with data contract name 'DataSection:http://schemas.example.com/Parse' is not expected.
或
The underlying connection was closed: The connection was closed unexpectedly.
我无法使用 KnownTypeAttribute 修饰接口(interface),因为 Contracts 项目不引用 Format 项目,引用会破坏设计。这就是我要使用配置的原因。
最佳答案
看看下面的代码
[ServiceContract]
[ServiceKnownType(typeof(SummarySectionFormatA))]
[ServiceKnownType(typeof(DataSectionFormatA))]
public interface IService {}
public class Service : IService {}
关于c# - 数据契约已知类型和一组相互继承的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11272672/