C# WCF DTO中的接口

C# WCF DTO中的接口,c#,wcf,C#,Wcf,我尝试传输一个DTO(WCF客户端到WCF服务器),它包含一个带有接口的子对象 我的代码: WCF服务方式: [OperationBehavior(TransactionScopeRequired = true)] public void SendTest(MyTestDto testDto) { ... } MyTestDto类: [Serializable] [DataContract(Name = "MyTestDto")] public class MyTestDto : ITes

我尝试传输一个DTO(WCF客户端到WCF服务器),它包含一个带有接口的子对象

我的代码:

WCF服务方式:

[OperationBehavior(TransactionScopeRequired = true)]
public void SendTest(MyTestDto testDto)
{
  ...
}
MyTestDto类:

[Serializable]
[DataContract(Name = "MyTestDto")]
public class MyTestDto : ITestDto
{
   [DataMember(IsRequired = true, Order = 1, Name = "MyTestDto")]
   [DataMemberValidation(IsRequired = true)]
   public ITest Test { get; set; }

}
ITest接口:

public interface ITest
{
    int Field1 {get;set;}
    int Field2 {get;set,}
}
问题是,如果我将MyTestDto从服务器传输到客户端,我总是会得到一个
FaultException
。我分析了WSDL文件,测试字段的类型为:
AnyType
。我想,这就是问题所在。我已经用一个抽象类替换了
ITest
,因此通信工作正常(当然,我必须用抽象类设置
ServiceKnownType
属性)


你能帮我吗?为什么它使用抽象类而不使用接口?

WCF使用具体类型,接口不能通过WCF序列化

只有在使用
ServiceKnownType
标记服务或使用
KnownType
属性标记数据协定时,才能将接口设置为抽象类。下面是一个例子

public abstract Test
{
    public int Field1 {get;set;}
    public int Field2 {get;set,}
}

public class SomeTest : Test
{ 
    ...
}

[ServiceKnownType(typeof(SomeTest))]
public class SomeService : ISomeService
{
     public void SendTest(Test test)
}

WCF使用具体类型,接口不能通过WCF序列化

只有在使用
ServiceKnownType
标记服务或使用
KnownType
属性标记数据协定时,才能将接口设置为抽象类。下面是一个例子

public abstract Test
{
    public int Field1 {get;set;}
    public int Field2 {get;set,}
}

public class SomeTest : Test
{ 
    ...
}

[ServiceKnownType(typeof(SomeTest))]
public class SomeService : ISomeService
{
     public void SendTest(Test test)
}

谢谢你的回答。我知道这一点,但我可以设置接口的具体类型,例如使用KnownType或ServiceKnownType属性?!无法通过电线发送接口;您需要将抽象类声明为基类而不是接口。谢谢您的回答。我知道这一点,但我可以设置接口的具体类型,例如使用KnownType或ServiceKnownType属性?!无法通过电线发送接口;您需要将抽象类声明为基类而不是接口。