[英]How can I retrieve the derived class from a list of abstract classes?
I have an application that displays several types of widgets. 我有一个显示几种类型的小部件的应用程序。 I pass the view the base abstract class, GraphWidget.
我将基本的抽象类GraphWidget传递给视图。 The goal is to loop through those, and create the appropriate display for each type of graph.
目标是遍历这些图形,并为每种图形创建适当的显示。
How would I go about looping through that collection and obtaining the appropriate information from the derived class so my view knows how to render each widget? 我将如何遍历该集合并从派生类中获取适当的信息,以便我的视图知道如何呈现每个小部件?
EDIT This is a .NET MVC5 application 编辑这是一个.NET MVC5应用程序
Sample code: 样例代码:
public abstract class GraphWidget {
public abstract string Display();
public string Title {get; set;}
public GraphWidget(string title){
this.Title = title;
}
}
public class BarGraph : GraphWidget{
public override string Display(){
return stuff...
}
}
So for example, if I have a mix of bar graphs and pie graphs, their Display() function will be different. 因此,例如,如果我混合使用条形图和饼图,则它们的Display()函数将有所不同。 I want to make sure, in my razor view, which is accepting an IEnumerable, that I can properly display each item.
我想在接受IEnumerable的剃须刀视图中确保可以正确显示每个项目。
You can use the "is" operator to test if your GraphWidgets are of a certain derived class: 您可以使用“ is”运算符来测试您的GraphWidgets是否属于某个派生类:
var graphs = new List<GraphWidget>{new BarGraph("Bar"), new PieGraph("Pie")};
foreach(var graph in graphs)
{
if (graph is BarGraph)
{ // it's a BarGraph
}
else if (graph is PieGraph)
{ // it's a PieGraph
}
}
If you need use them as the derived class, then you can use the "as" operator: 如果需要将它们用作派生类,则可以使用“ as”运算符:
/* Note: if graph is actually of type PieGraph,
then barGraph would be null */
var barGraph = graph as BarGraph;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.