我应该如何声明一个 class 类型列表?
How should I declare a class type list?
我有这个示例方法,我实际上是在另一个解决方案中实现它。
我想声明一个根据 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 并从中继承。然后创建一个基础列表 class 并像这样添加您的项目:
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;
}
我有这个示例方法,我实际上是在另一个解决方案中实现它。
我想声明一个根据 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 并从中继承。然后创建一个基础列表 class 并像这样添加您的项目:
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;
}