ToString()不返回预期的字符串

时间:2009-01-30 15:19:18

标签: c# .net generics


using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication3Generics
{
    class Program
    {
        static void Main(string[] args)
        {
            ScheduleSelectedItems sitems = new ScheduleSelectedItems("Yusuf");
            ScheduleSelectedItemsList slist = new ScheduleSelectedItemsList();
            slist.Items.Add(sitems);
            Console.Write(slist.Items[0].ToString());
            Console.ReadKey();
        }
    }
    public class ScheduleSelectedItems
    {
        private string Ad;

        public ScheduleSelectedItems(string ad)
        {
            Ad = ad;
        }
    }

    public class ScheduleSelectedItemsList
    {
        public List Items;

        public ScheduleSelectedItemsList()
        {
            Items = new List();
        }
    }
}

如何在我的控制台上添加“yusuf”?

4 个答案:

答案 0 :(得分:15)

public class ScheduleSelectedItems
    {
        private string Ad;

        public ScheduleSelectedItems(string ad)
        {
            Ad = ad;
        }

        public override string ToString()
        {
            return this.Ad;
        }
    }

答案 1 :(得分:5)

BFree说了什么,略微修改使其成为单数而不是复数:

public class ScheduleSelectedItem
{
    private string Ad;

    public ScheduleSelectedItem(string ad)
    {
        Ad = ad;
    }
    public override string ToString()
    {
        return this.Ad;
    }
}

此外,您需要为列表添加“添加”方法。当你在它的时候,为什么不继承列表类:

public class ScheduleSelectedItemsList : List<ScheduleSelectedItem>
{

}

或者你可以创建一个类型别名:

using ScheduleSelectedItemsList = List<ScheduleSelectedItem>;

无论哪种方式,您都可以使用这样的新代码:

class Program
{
    static void Main(string[] args)
    {
        var slist = new ScheduleSelectedItemsList() 
        { 
            new ScheduleSelectedItem("Yusuf") 
        };

        //write every item to the console, not just the first
        slist.All(item => Console.Write(item.ToString()) );
        Console.ReadKey();
    }
}

答案 2 :(得分:3)

将此添加到您的ScheduleSelectedItems课程:

    public override string ToString() {
        return Ad;
    }

告诉系统应该如何格式化这样的对象。

答案 3 :(得分:2)

您需要覆盖ScheduleSelectedItems的toString()方法才能返回“广告”。