【问题标题】:Returning Dictionary using webservice使用网络服务返回字典
【发布时间】:2013-11-25 21:44:18
【问题描述】:

我正在寻找一些关于使用 WebService 中的 csv 文件填充字典的帮助,但是我无法返回结果。

我试图将字典分成两个单独的列,这似乎可行,但我无法返回值,因为有两个而不是一个。

代码如下:

{
    StreamReader streamReader = new StreamReader("T:/4 Year WBL/Applications Development/Coursework 2/2b/Coursework2bwebservice/abrev.csv");

    [WebMethod]
    public string Dictionary()
    {
        string  line;
       Dictionary<string, string> dictionary = new Dictionary<string,string>();
       while ((line =  streamReader.ReadLine()) !=null)
       {
       string[] columns = line.Split(','); 
       dictionary.Add(columns[0], columns[1]);

       return dictionary;    
       }
    }

我收到错误“无法隐式转换类型System.Collections.Generic.Dictionary&lt;string,string to string&gt;"

任何想法都会很棒,感谢您抽出宝贵时间。

【问题讨论】:

    标签: dictionary c#-3.0 streamreader


    【解决方案1】:
    public string Dictionary()
    

    正在返回错误的签名。您需要返回一个实际的字典:

    public Dictionary<string, string> Dictionary()
    

    还有,这个

    while ((line =  streamReader.ReadLine()) !=null)
    

    似乎有点古怪。您还将在循环内返回您的dictionary。让我们试试吧:

    line = streamReader.Readline();
    while (line !=null)
    {
       string[] columns = line.Split(','); 
       dictionary.Add(columns[0], columns[1]);
       line = streamReader.Readline();
    }
    return dictionary;  
    

    话虽如此,在 web 方法中返回一个实际的字典对象可能没有多大意义。您真正想要的是一个 XML 序列化的字典或列表。请参阅此处:https://www.google.com/search?q=return+dictionary+in+web+method 了解更多信息。

    【讨论】:

    • 非常感谢,这非常有帮助并且可以解决。尽管您说的不正确,因为网络服务不接受字典类。我将查看序列化的 xml 字典并从那里开始。再次感谢您。
    猜你喜欢
    • 1970-01-01
    • 2012-01-02
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    相关资源
    最近更新 更多