如何在数据结构中使用类abc作为对象说“List”?

时间:2011-12-22 07:10:51

标签: c#

public class abc
    {
        public static void main()
        {
            List<abc> list = new List<abc>() ;
        }
    }

我想在列表中添加我在班级中使用的所有字段,并使用列表显示它们.plzz告诉..如何在c#中编写代码?

2 个答案:

答案 0 :(得分:1)

首先创建一个abc

的实例
abc instance = new abc();
//then set the properties
abc.Property1 = "Some value";
//similarly set the value of rest of the properties.

//insert this instance in your list by using add method
list.Add(instance);

//iterate through each instance in list

foreach(abc instance in list)
{
    //print value of a property
    console.Writeline(abc.Property1);
    //similarly other properties
}

答案 1 :(得分:1)

如果要打印出对象的所有属性,则可能需要使用反射代码,例如:

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

    //....

var list = new List<abc>();
list.Add(new abc() {Name="instance 1"});
list.Add(new abc() {Name="instance 2"});

foreach (var instance in list)
{
    foreach (var property in instance.GetType().GetProperties())
    {
        Console.WriteLine(property.Name + "=" +
                          property.GetValue(instance, null));
    }
}