我有这个示例方法,实际上是在另一个解决方案中实现它。
我想声明一个列表,该列表将根据switch()的值采用不同的类型,应该采取什么措施?
class ReportStrings
{
string date;
string name;
}
class ReportIntegers
{
int number;
int amount;
}
public void main()
{
List<SOMETHING> LReport;
string reportname; //let's think it has a value
switch (reportname)
{
case "ReportOne": LReport = new List<ReportStrings>; break;
case "ReportTwo": LReport = new List<ReportIntegers>; break;
}
Console.WriteLine(LReport.Count());
}
只需使用某种基类并从中继承。然后创建基类的列表,并添加您的项目,如下所示:
class ReportBase { }
class ReportStrings:ReportBase
{
string date;
string name;
}
class ReportIntegers:ReportBase
{
int number;
int amount;
}
public void main()
{
List<ReportBase> LReport;
string reportname=null; //let's think it has a value
LReport=GetList(reportname);
Console.WriteLine(LReport.Count());
}
private List<ReportBase> GetList(string reportname)
{
var LReport = new List<ReportBase>();
switch (reportname)
{
case "ReportOne":
LReport.Add(new ReportStrings(){ /* ...add your values here... */};
break;
case "ReportTwo":
LReport.Add(new ReportIntegers(){ /*...add your values here... */};
break;
}
return LReport;
}