【问题标题】:Trying to string.Join an IList尝试字符串。加入 IList
【发布时间】:2012-04-24 03:20:07
【问题描述】:

我正在尝试将第一个示例 http://www.dotnetperls.com/convert-list-string 实现到我的方法中,但我很难匹配该方法的第二个参数:

string printitout = string.Join(",", test.ToArray<Location>);

错误信息:

The best overloaded method match for 'string.Join(string,
System.Collections.Generic.IEnumerable<string>)' has some invalid arguments

所有的 IList 接口也是用 IEnurmerable 实现的(除非有人希望我在此列出)。

class IList2
{
    static void Main(string[] args)
    {

     string sSite = "test";
     string sSite1 = "test";
     string sSite2 = "test";

     Locations test = new Locations();
     Location loc = new Location();
     test.Add(sSite)
     test.Add(sSite1)
     test.Add(sSite2)
     string printitout = string.Join(",", test.ToArray<Location>); //having issues calling what it needs.

     }
 }
string printitout = string.Join(",", test.ToArray<Location>);


public class Location
{
    public Location()
    {

    }
    private string _site = string.Empty;
    public string Site
    {
        get { return _site; }
        set { _site = value; }
    }
}

public class Locations : IList<Location>
{
    List<Location> _locs = new List<Location>();

    public Locations() { }

    public void Add(string sSite)
    {
        Location loc = new Location();
        loc.Site = sSite;
        _locs.Add(loc);
    }
 }

编辑: 好的,使用 "string.Join(",", test);"工作,在我用复选标记关闭它之前,出于某种原因我的输出,输出:

“Ilistprac.Location,Ilistprac.Location,Ilistprac.Location”

出于某种原因,而不是列表中的内容。

【问题讨论】:

    标签: linq c#-4.0 interface


    【解决方案1】:

    试试:

    string printitout = string.Join(",", test);
    

    【讨论】:

    • 感谢您的回复,我收到此错误消息:以下方法或属性之间的调用不明确:'string.Join(string, System.Collections.Generic.IEnumerable)' 和 'string.Join(string, params object[])'
    【解决方案2】:

    你需要在ToArray&lt;Location&gt;之后加上括号-()

    string printitout = string.Join(",", test.Select(location => location.Site).ToArray()); 
    

    【讨论】:

    • 啊 lambda,我对此并不擅长,但我正在努力学习它!这实际上也正确输出了 IList 中的内容。
    【解决方案3】:

    如果你的Locaions 类型实现了IEnumerable,你就不需要ToArray

    string printiout = String.Join(",", test);
    

    【讨论】:

      【解决方案4】:

      您根本不需要ToArray()(因为看起来您使用的是.Net 4.0),因此您可以拨打电话

      string.Join(",", test);
      

      【讨论】:

      • 就在我回答这个问题之前。我的输出输出为:“Ilistprac.Location,Ilistprac.Location,Ilistprac.Location”,而不是由于某种原因列表中的列表项。
      • 您尚未在 Location 对象上覆盖 ToString(),因此您将获得默认行为。
      • @dlev - 这意味着没有在对象上覆盖 ToString() 是什么意思?答案没有说明重写 ToString()。你如何解决这个问题?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-28
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      • 1970-01-01
      • 2021-12-05
      • 2013-05-14
      相关资源
      最近更新 更多