所以,我正在处理涉及列表的类的一些代码。
我目前有这个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace excercise_1
{
class Program
{
static void Main(string[] args)
{
Card c1 = new Card("1112211", "Jhon", "Brown", "Wollongong", 2500, 1500);
Card c2 = new Card("1111457", "Sibel", "Yilmaz", "Figtree", 3251, 3000);
Card c3 = new Card("3333333", "Suzan", "Yilmaz", "Gywnville", 3000, 5000);
Card c4 = new Card("4444444", "Bob", "Brown", "Balgownie", 1457, 2000);
c1.Print();
c2.Print();
List<Card> Cards = new List<Card>();
Cards.Add(c3);
Cards.Add(c4);
}
}
class Card
{
public string id;
public string first_name;
public string family_name;
public string suburb;
public int postcode;
public int balance;
public Card (string id, string first_name, string family_name, string suburb, int postcode, int balance)
{
this.id = id;
this.first_name = first_name;
this.family_name = family_name;
this.suburb = suburb;
this.postcode = postcode;
this.balance = balance;
}
public void Print()
{
Console.WriteLine(this.id);
Console.WriteLine(this.first_name);
Console.WriteLine(this.family_name);
Console.WriteLine(this.suburb);
Console.WriteLine(this.postcode);
Console.WriteLine(this.balance);
}
}
}
我需要能够打印名为Cards的列表。我尝试了各种各样的方法,但没有任何工作,我变得越来越沮丧。如果有人能够提供帮助,将不胜感激。
答案 0 :(得分:1)
你可以这样做:
Cards.ForEach(x=>x.Print());
或者像这样:
foreach (Card card in Cards)
{
card.Print();
}
答案 1 :(得分:1)
1)实现ToString()
的覆盖
像http://msdn.microsoft.com/en-us/library/ms173154(v=vs.80).aspx
2)有许多方法可以像上面已经指出的那样迭代List
3)尝试向Google询问它会大大缩短您在询问和获得答案之间的时间,也许您会找到一两个指南...... like答案 2 :(得分:0)
为什么不使用简单的循环?
foreach(var card in Cards)
card.Print();
顺便说一下,您可以考虑为您的班级而不是ToString
方法覆盖Print
。
答案 3 :(得分:0)
只需使用Foreach进行打印。
foreach(var card in Cards)
{
card.print();
}
请: - 将所有这些公共变量设为私有。
public string id; // private
public string first_name; // private
public string family_name; // private
public string suburb; // private
public int postcode; // private
public int balance; // private
答案 4 :(得分:0)
我不会自己编写打印方法。 您可以使用TypeDescriptor。
public static void PrintList(IEnumerable<object> values)
{
foreach (var obj in values)
{
string objString = "";
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
{
string name = descriptor.Name;
object value = descriptor.GetValue(obj);
objString += string.Format(" {0} = {1} ", name, value);
}
Console.WriteLine(objString);
}
}