简体   繁体   中英

Can I expose a DataMember of a class that is not a DataContract?

Can I do something like this:

public abstract class DeletableEntity
{
    [DataMember]
    public bool Delete { get; set; }
}

[DataContract]
public class MyClass : DeletableEntity
{
    [DataMember]
    public int ID { get; set; }
}

I really only need DeletableEntity so others can inherit from it, so it doesn't need to go over WCF, can I send its Delete member with my MyClass without having to send the DeletableEntity as well?

No that should not be possible. From your requirements it would be simpler to use interfaces. Also, as an advise please consider using Known Types. This is not really directly related to you problem but it will allow you to use 'polymorphism' over wcf. More details can be obtained here: http://msdn.microsoft.com/en-us/magazine/gg598929.aspx

You have a couple of options with how the DataContractSerializer handles serialization:

  1. Do nothing-- default behavior in .NET 4.0 and later is to send all public members if NO declarations are made about [DataContract] or [DataMember].
  2. Declare DeletableEntity as a [DataContract] and declare the serializable [DataMembers]. Once you say something, WCF assumes you want to say more.

You'll probably want to do #2. Once you do that, add on a [KnownTypes] attribute if you have any WCF methods that take a DeletableEntity and it's derived types. You'll probably just want to use the string version of KnownTypes that passes a static method name. The static method can then use reflection on the assembly to pull out all types that derive from DeletableEntity such that the method catches any new items that are added as you code.

If you want the above, I recommend the following code:

[DataContract]
[KnownType("GetKnownTypes")]
public abstract class DeletableEntity
{
  [DataMember]
  public bool Delete { get; set; }

  public static Type[] GetKnownTypes()
  {
    return (from type in typeof (DeletableEntity).Assembly.GetTypes()
            where typeof (DeletableEntity).IsAssignableFrom(type)
            select type).ToArray();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM