gpt4 book ai didi

c# - 打印不同对象的列表

转载 作者:行者123 更新时间:2023-11-30 14:28:01 24 4
gpt4 key购买 nike

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

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.

}

}
}

最佳答案

您应该使用“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);
}
}

关于c# - 打印不同对象的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30535622/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com