打印各种对象的列表

时间:2015-05-29 17:27:16

标签: c# collections polymorphism

我正在尝试返回两种不同列表类型的组合列表。所有子类都来自同一个没有任何代码的基类。 我可以看到基类中的项目。但是,现在应该有什么。

class BaseClass
{
   //empty no code
}
class ChildClassA : BaseClass
{

     public string Name {get; set;}
     public DateTime DateAccess {get; set;}

     public ChildClassA(string name, DateTime dateAccess){
        Name = name; 
        DateAccess = dateAccess;
     }


     public List<ChildClassA> GetListMethod()
     {
       //block of code

       return List<ChildClassA>;  // each items have Name and DateAccess
     }

}

class ChildClassB: BaseClass
{

     public string Group {get; set;}
     public DateTime SessionDuration {get; set;}
     public string Report{get; set;}

     public ChildClassB(string group, DateTime sessionDuration, string report)
     {
        Group = group; 
        SessionDuration = sessionDuration;
        Report = report; 
     }


   public List<ChildClassB> GetListMethod()
   {
     //block of code

    return List<ChildClassB>;   // each item has Group, SessionDuration and Report
   }
}

class CombineListClass
{
    public List<BaseClass> GetCombineList()
    {

        List<BaseClass> listFromBaseClass = new List<BaseClass>();

        ChildClassA a = new ChildClassA(); 
        var listFromA = a.GetListMethod();

        ChildClassB b = new ChildClassB(); 
        var listFromB = b.GetListMethod();

        listFromBaseClass.AddRange(listFromA);
        listFromBaseClass.AddRange(listFromB);

        foreach(var item in listFromBaseClass)
        {

           //print the item from each listFromBaseClass
           // needs to print Name, DateAccess, Group, SessionDuration, Report in one output file.

        }

   }
}

2 个答案:

答案 0 :(得分:3)

您应该使用“is”关键字检查对象类型并将其强制转换并分别显示正确的值:

 foreach(var item in listFromBaseClass)
    {

       //print the item from each listFromBaseClass
       // needs to print Name, DateAccess, Group, SessionDuration, Report in one output file.
        if (item is ChildClassA)
        {
              Console.WriteLine(((ChildClassA)item).Name);
        }
        else if (item is ChildClassB)
        {
              Console.WriteLine(((ChildClassB)item).Group);
        }
    }

答案 1 :(得分:3)

你可以让它们各自实现一个接口:IReportable

interface IReportable
{
    Row GenerateReportRow();
}

class ChildClassA : IReportable
{
    Row GenerateReportRow()
    {
        //whatever important items
    }
}

然后你可以利用polymorphism的魔力。

foreach(var item in listFromBaseClass)
{
   item.GenerateReportRow();
}

否则你可能只有一个对象集合,如果他们真的没有共享任何东西,除了想要将它们全部存储在同一个地方。