简体   繁体   中英

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. 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

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. I want to make sure, in my razor view, which is accepting an IEnumerable, that I can properly display each item.

You can use the "is" operator to test if your GraphWidgets are of a certain derived class:

    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:

    /* Note: if graph is actually of type PieGraph, 
             then barGraph would be null */
    var barGraph = graph as BarGraph; 

As I understand you, you can use LINQ method OfType :

var list = new List<GraphWidget>();
var badList = list.OfType<BarGraph>().ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM