English 中文(简体)
ToString() 没有返回预期的字符串。
原标题:
  • 时间:2009-01-30 15:19:17
  •  标签:

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”?

问题回答
public class ScheduleSelectedItems
    {
        private string Ad;

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

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

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

将此添加到您的 ScheduleSelectedItems 类中:

    public override string ToString() {
        return Ad;
    }

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

你需要覆盖ScheduleSelectedItems的toString()方法以返回Ad。





相关问题
热门标签