如何从完全限定的数据类型中获取值?

时间:2015-02-23 18:36:32

标签: c#

我有像这样的Program.cs类

var products = new List<object>();
var f1 = new Fruit("Apple", 25.34, 5);
products.Add(f1);

foreach (var item in products)
{
   Console.WriteLine(item);
}

这是我的Fruit.cs类

public Fruit(string name, double weight, int quantity)
{
   Name = name;
   Weight = weight;
   Quantity = quantity;
}

  public string Name { get; set; }

  public double Weight { get; set; }

  public int Quantity { get; set; }

当我运行这个程序时,它写在屏幕上

ConsoleApplication1.Fruit   

我的问题是如何打印我存储在产品列表中的值(Apple,25.34,5)?

感谢任何帮助。感谢。

5 个答案:

答案 0 :(得分:3)

覆盖ToString()方法:

public override ToString()
{
    return this.Name + "," + this.Weight + "," + this.Quantity
}

答案 1 :(得分:1)

您可以尝试这样的事情:

foreach (var item in products)
{
   Console.WriteLine(String.Format("Name: {0}, Weight: {1}, Quantity: {2}",
                                  ((Fruit)item).Name, 
                                  ((Fruit)item).Weight, 
                                  ((Fruit)item).Quantity));
}

或者您可以覆盖ToString类的Fruits方法:

public class Fruit
{
    public string Name { get; set; }

    public double Weight { get; set; }

    public int Quantity { get; set; }

    public Fruit(string name, double weight, int quantity)
    {
       Name = name;
       Weight = weight;
       Quantity = quantity;
    }

    public override string ToString()
    {
        return String.Format("Name: {0}, Weight: {1}, Quantity: {2}", Name, Weight, Quantity);
    }
}

按原样显示您的foreach语句:

foreach (var item in products)
{
    Console.WriteLine(item);
}

您获得ConsoleApplication1.Fruits的原因是因为ToString方法的默认实现(在上面的Console.WriteLine下引用)会返回该类型的全名。宾语。重写此方法,您可以使其返回您想要的任何内容。

答案 2 :(得分:1)

你可以这样做

foreach (var item in products)
{
   Console.WriteLine("Name: {0}, Weight: {1}, Quantity: {2}",
                                  ((Fruit)item).Name, 
                                  ((Fruit)item).Weight, 
                                  ((Fruit)item).Quantity);
}

或者你可以在Fruit Class中覆盖你的ToString方法并像这样改变它

public override string ToString()
{
     return Name+":"+Weight+":"+Quantity;
}

答案 3 :(得分:0)

只需写:Console.WriteLine(item.Name,item.Weight,item.Quantity);

更多信息: 产品列表中的每个项目都是Fruit类型。因此,如果要打印正确的信息,则需要访问Fruit(item)对象的属性(Name,Weight,Quantity)。

foreach (var item in products)
{
   Console.WriteLine((Fruit)item.Name, (Fruit)item.Weight, (Fruit)item.Quantity);
}

答案 4 :(得分:0)

变化

var products = new List<object>();

var products = new List<Fruits>();

这样你就可以这样写,所以会像桌子一样显示:

 var products = new List<object>();
        var f1 = new Fruits("Apple", 25.34, 5);
        var f2 = new Fruits("Orange", 18.19, 3);
        products.Add(f1);
        products.Add(f2);
        String ss = "Item\t\tWeight\t\tQty\n";
        for (int i = 0; i < 60; i++) ss += "-";

        Console.WriteLine(ss);

        foreach (var item in products)
        {
            Console.WriteLine(item.Name.ToString() + "\t\t" + item.Weight.ToString() + "\t\t" + item.Quantity.ToString());
        }