【问题标题】:Trying to string.Join an IList and outputting the results to console尝试字符串。加入 IList 并将结果输出到控制台
【发布时间】:2012-04-12 16:57:44
【问题描述】:

使用 "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; }

    }


 }

【问题讨论】:

    标签: linq c#-4.0


    【解决方案1】:

    您需要为Location 提供一个有用的ToString 实现,因为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 个值,它看起来需要格式化,谢谢!
    • 这并不是关于返回多个值。这是关于你的类型应该如何表示为stringJoin 在序列中的每个Location 实例上调用ToString。类的默认字符串表示是类型名称。如果您想要其他任何内容,则需要为该类型覆盖 ToString
    • 知道了,我没有意识到默认实现是什么,需要重写才能将其转换为字符串。我在返回这些值时遇到了问题,但是让它们像那样格式化就可以了
    【解决方案2】:

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

    public override string ToString()
    {
        return Site;
    } 
    

    【讨论】:

      猜你喜欢
      • 2012-04-24
      • 1970-01-01
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      • 2011-11-01
      • 2018-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多