how to mark an interface as DataContract in WCF

你。 提交于 2019-12-01 03:08:20

As far as I know using interfaces as datacontracts is not possible. You may use a base class and add knowntype attributes on the otherhand.

Fer: Everything is Possible with the right design.

If the issue is:

a class is a data contract

&&

1 or more of its properties must be an interface...

public interface ICustomInterface
{
    int Property1 {get;set}
}

[DataContract]
public class MyClass
{
     [DataMember(Name="_myInterface")]
     public ICustomInterface MyInterface {get;set;}
}

The issue is that when the de-serialization occurs -- There is no way to turn the data into a class that implements ICustomInterface.

The Solution is to create a concrete class that does Implement the interface, and cast the getter/setter of the public property (that is of type interface) into a private property of the concrete class.

public class CustomInterfaceImplementor: ICustomInterface
{
     public int Property1 {get;set;}
}

[DataContract]
public class MyClass
{
     [DataMember(Name="_myInterface")]
     private CustomInterfaceImplementor _MyInterface;
     public ICustomInterface MyInterface
     {
          get {return (_MyInterface as ICustomInterface);}
          set {_MyInterface = (value as CustomInterfaceImplementor);}
     }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!