使用“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; }
}
}
答案 0 :(得分:3)
您需要为ToString
提供有用的Location
实施,因为Join
正在为每个元素调用该实现。默认实现只返回类型的名称。见documentation。
所以,如果您有类似
的类型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
答案 1 :(得分:3)
如果您想保留当前的方法,则必须覆盖ToString()
inc Location
课程以提供一些有意义的输出,例如:
public override string ToString()
{
return Site;
}