`DataContractSerializer` 将子类反序列化为基类

问题描述 投票:0回答:1

我的服务器上有以下内容:

[DataContract]
public class Base { }

[OperationContract]
void DoSth(Base base) { }

我的客户:

class Child : Base { }

使用

DoSth(child)
调用服务器时,出现序列化异常,因为服务器不知道
Child

System.ServiceModel.CommunicationException: There was an error while trying to serialize parameter http://tempuri.org/:base. The InnerException message was 'Type 'Child' with data contract name 'Child:http://schemas.datacontract.org/2004/07/Client' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'.  Please see InnerException for more details.
 ---> System.Runtime.Serialization.SerializationException: Type 'Child' with data contract name 'Child:http://schemas.datacontract.org/2004/07/Client' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

而且我不想让它知道,因为服务器只使用

Base
的属性。我怎样才能做到这一点?

我知道,我可以创建一个新的

Base
对象并复制所有属性,但这并不是很优雅。

c# wcf datacontractserializer
1个回答
0
投票

我用WCF的模板示例进行了测试。

我在客户端的Reference.cs中继承:

这是一个例子:

服务器端:

    [DataContract]
    public class CompositeType
    {
   
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]    
            public bool BoolValue
            {
                get { return boolValue; }
                set { boolValue = value; }
            }

        [DataMember]
        public string StringValue
{
    get { return stringValue; }
    set { stringValue = value; }
}
        }

客户端:

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
    [System.Runtime.Serialization.DataContractAttribute(Name = "CompositeType", Namespace = "http://schemas.datacontract.org/2004/07/WcfService4")]
    [System.SerializableAttribute()]
    public class Child : CompositeType
    {
        [DataMember]
        public bool BoolValue { get; set; }
        [DataMember]
        public string StringValue { get; set; }
    
    }

现在测试程序可以运行了,你可以试试我的方法。

© www.soinside.com 2019 - 2024. All rights reserved.