将派生类转换为基类以进行WCF序列化

将派生类转换为基类以进行WCF序列化,wcf,serialization,base,derived,upcasting,Wcf,Serialization,Base,Derived,Upcasting,我有两门课 [Serializable] [DataContract] public class A { [DataMember] public string _a { get; set; } [DataMember] public bool _b { get; set; } } [Serializable] public

我有两门课

[Serializable]
[DataContract]
public class A
{
    [DataMember]
    public string _a                                   { get; set; }
    [DataMember]
    public bool _b                                     { get; set; }
}

[Serializable]
public class B : A
{
    [NonSerialized]
    [XmlIgnore] 
    private C _c;
}
。。。我有一个WCF服务:

public interface IClient
{

    [ServiceKnownType(typeof(A))]
    [OperationContract(IsOneWay = true)]
    void Somefunction(List<A> listofA);
}

List<A> listofA = new List<A>();

foreach (B instanceofb in somestore.Values)
{
    listofA.Add(Convert(instanceofb));
}

Client.Somefunction(listofA);
List listofA=新列表();
foreach(somestore.Values中的B instanceofb)
{
Add(Convert(instanceofb));
}
Client.Somefunction(listofA);

如果您的对象是B的实例,它们将始终被序列化为B的实例-这就是序列化的要点。如果要忽略
\u c
,请尝试以下操作:

[DataContract]
public class B : A
{
    private C _c;
}
如果类用
DataContract
标记,则只有用
DataMember
标记的属性/字段被序列化-我不确定
Serializable
如何与父级一起使用
DataContract

您还必须使用此命令告知服务和客户可以使用
B

public interface IClient
{
    [ServiceKnownType(typeof(B))]
    [OperationContract(IsOneWay = true)]
    void Somefunction(List<A> listofA);
}
公共接口IClient
{
[ServiceKnownType(类型(B))]
[运营合同(IsOneWay=true)]
void Somefunction(列表a);
}

如果您只想发送
A
实例,则必须创建
A
实例,而不是
B
实例-在您的场景中,这实际上意味着转换。

请编辑注意-如果您认为提供的代码段错误,请添加带有更正代码的答案。您好,您可以在这里提供帮助吗?
List<A> listofA = new List<A>();

foreach (B instanceofb in somestore.Values)
{
    listofA.Add(Convert(instanceofb));
}

Client.Somefunction(listofA);
[DataContract]
public class B : A
{
    private C _c;
}
public interface IClient
{
    [ServiceKnownType(typeof(B))]
    [OperationContract(IsOneWay = true)]
    void Somefunction(List<A> listofA);
}