开发者

Converting a Derived Class to Base Class for WCF Serialisation

开发者 https://www.devze.com 2023-04-04 05:32 出处:网络
I have two classes... [Serializable] [DataContract] public class A { [DataMember] public string _a{ get; set; }

I have two classes...

[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;
}

... and I have a WCF service:

public interface IClient
{

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

I need to send a list of A to the client, but I only have a list of B. I don't care about the "_c" field. I would've thought this is as simple as:

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

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

Client.Somefunction(listofA);

But the derived type of the object is stored within t开发者_JS百科he base type instance in the list. WCF seems to try to deserialise and fail because C is not serializable (even though I've marked it as ignored). I get no response on the client side, and the server side method just falls through.

But I can create and send (and receive on the client) type A though:

List<A> listofA = new List<A>() { new A() };
Client.Somefunction(listofA);

Is there any way short of the cringeworthy (which works):

public A Convert(B _instanceofb)
{
  A _instanceofA = new A();
  A._a = _instanceofb._a;
  A._b = _instanceofb._b;
  return A;
}

and ..

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

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

Client.Somefunction(listofA);


If your objects are instances of B they will always be serialized as instances of B - that is the point of serialization. If you want to ignore _c try this:

[DataContract]
public class B : A
{
    private C _c;
}

If class is marked with DataContract only properties / fields marked with DataMember are serialized - I'm not sure how Serializable works together with parent using DataContract.

You must also use this to tell service and client that B can be used:

public interface IClient
{
    [ServiceKnownType(typeof(B))]
    [OperationContract(IsOneWay = true)]
    void Somefunction(List<A> listofA);
}

If you want to send only A instances you must create A instances not B instances - in your scenario it really means converting.

0

精彩评论

暂无评论...
验证码 换一张
取 消