【问题标题】:How to return a List<> from a WCF call如何从 WCF 调用返回 List<>
【发布时间】:2014-12-16 04:47:30
【问题描述】:

我刚刚开始使用 WCF。我已经创建了 WCF 服务并将其托管在控制台应用程序中。

我的自定义类在服务和客户端之间共享。

[Serializable]
public class clsPlinker
{
    [Serializable]
    public class Game : Object
    {
        public Game(string name, string desc, int GameNum)
        {
            _Name = name;
            _Desc = desc;
            _GameNum = GameNum;
        }
    }
}

这是我的界面

[ServiceContract]
public interface IPlinkerWCFservice
{
    [OperationContract]
    List<clsPlinker.Game> GetGameList();
}

这是我的服务

public class PlinkerWCFservice : IPlinkerWCFservice
{
    public List<clsPlinker.Game> GetGameList()
    {
        List<clsPlinker.Game> lstGames = new List<clsPlinker.Game>();
        // do stuff to load the lstGames
        return lstGames;
    }
}

在我的 Windows 客户端应用程序中,我调用了服务引用

PlinkerWCFservice.PlinkerWCFserviceClient wcfTest = new PlinkerWCFservice.PlinkerWCFserviceClient("NetTcpBinding_IPlinkerWCFservice");
List<clsPlinker.Game> lstGames = wcfTest.GetGameList().ToList();

代码无法编译,出现以下错误:

不能隐式转换类型 System.Collections.Generic.List&lt;TabletController.PlinkerWCFservice.clsPlinkerGame&gt;System.Collections.Generic.List&lt;PlinkerCommon.clsPlinker.Game&gt;

TabletController 是我的 WinForms 应用程序的命名空间。

在另一种方法中,我可以返回单个 clsPlinker.Game,但尝试返回 List 让我很困惑。我已经搜索了几个小时,但无济于事。我做错了什么。

【问题讨论】:

    标签: c# winforms wcf list serialization


    【解决方案1】:

    添加服务引用时,将集合类型从 System.Array 更改为 System.Collections.Generic.List 并在所有引用的程序集中重用类型。

    【讨论】:

    • 更改集合类型不会改变任何东西。如果我选中 Reuse Types 复选框,我的服务引用中的所有方法都会消失。
    【解决方案2】:

    这样改,

    您的结果是TabletController.PlinkerWCFservice.clsPlinkerGame 类型,但您的结果是clsPlinker.Game

    List<TabletController.PlinkerWCFservice.clsPlinkerGame> lstGames = wcfTest.GetGameList().ToList();
    

    【讨论】:

    • 解决了编译错误,谢谢!现在我怎样才能将它类型转换回 clsPlinker.game 对象?由于客户端和服务器都引用同一个类,我不应该这样做吗?如果我在迭代列表时尝试将它们转换为 clsPlinker.Game 对象,我会得到同样的错误。
    • 我最终没有在项目之间共享课程。检索结果后,我只需将值分配给新的 clsPlinker.Game 对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多