如何通过WCF传递List <interface>?</interface>

时间:2009-08-03 05:07:34

标签: wcf interface

我有一个WCF服务,我试图在我的一个操作合同中返回一个List(IWatchable是我建立的自定义界面)。当我在客户端上测试服务时,该方法返回 object[] 而不是 List<IWatchable> 。是否可以返回IWatchable列表,因为IWatchable是与WCF的接口?

方法:

public List<IWatchable> GetWorkload( Guid nodeId, int maximum )

IWatchable:

public interface IWatchable
{
    string ActionName { get; set; }
    Guid ActionReference { get; set; }
}

希望更多信息会有所帮助...

我有一个派生界面:

public interface IAMRAWatchable: IWatchable

来自IAMRAWatchable的三个具体实现:

public class InstrumentationWatch: IAMRAWatchable
public class OutputWatch: IAMRAWatchable
etc...

在我的WCF方法中,返回 List<IWatchable> 我想向客户端发送InstrumentationWatchOutputWatch ...这是可能还是我这是错误的方式吗?


解决

感谢John,我找到了解决方案。 KnownType 因为我使用 List<IWatchable> 而无法正常工作 - 所以我将我的列表包装到一个新类中并添加了属性。我需要重新考虑我的代码,但对于其他感兴趣的人来说,这是一个类:

[DataContract]
[KnownType( typeof( InstrumentationWatch ) )]
[KnownType( typeof( OutputWatch ) )]
public class WorkInfo
{
    [DataMember]
    public List<IWatchable> WorkQueue { get; set; }
}

和我的WCF方法:

public WorkInfo GetWorkload( Guid nodeId, int maximum )

1 个答案:

答案 0 :(得分:9)

永远不能序列化接口。这只是对行为的描述。

您可以序列化实现该接口的对象,但您必须告诉WCF它们的类型是什么。请参阅Data Contract Known Types