1

使用 "string.Join(",", test);" 有效,但由于某种原因,我得到以下输出:

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

我尝试了 ToString、Convert.ToString 等,但仍然得到该输出。

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

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

     string sSite = "test";

 string sBldg = "test32";
     string sSite1 = "test";
     string sSite2 = "test";

     Locations test = new Locations();
     Location loc = new Location();
     test.Add(sSite, sBldg)
     test.Add(sSite1)
     test.Add(sSite2)
     string printitout = string.Join(",", test); //having issues outputting whats on the list

     }
 }
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;

        loc.Bldg = sBldg;
        _locs.Add(loc);
    }

    private string _bldg = string.Empty;

    public string Bldg

    {

        get { return _bldg; }

        set { _bldg = value; }

    }


 }
4

2 回答 2

3

您需要为每个元素提供一个有用的实现ToString。默认实现将只返回类型的名称。请参阅文档LocationJoin

所以如果你有这样的类型

class SomeType
{
    public string FirstName { get; private set;  }
    public string LastName { get; private set; }

    public SomeType(string first, string last)
    {
        FirstName = first;
        LastName = last;
    }

    public override string ToString()
    {
        return string.Format("{0}, {1}", LastName, FirstName);
    }
}

您需要指定应如何将其表示为字符串。如果你这样做,你可以像这样使用 string.Join 来产生下面的输出。

var names = new List<SomeType> { 
    new SomeType("Homer", "Simpson"), 
    new SomeType("Marge", "Simpson") 
};

Console.WriteLine(string.Join("\n", names));

输出:

Simpson, Homer
Simpson, Marge
于 2012-04-12T17:04:35.107 回答
3

如果您想保持当前的方法,您必须覆盖ToString()您的类以提供一些有意义的输出,例如:Location

public override string ToString()
{
    return Site;
} 
于 2012-04-12T17:04:37.697 回答