Cast an object into an object from a derived class

前端 未结 4 1471
野的像风
野的像风 2021-01-25 06:15

I have a class Record that works fine:

public class Record 
{
    protected string table;
    protected string idcolumn;
    public Record(string _t         


        
4条回答
  •  逝去的感伤
    2021-01-25 06:51

    If you get an InvalidCastException then theRecord is not an Order and you can't cast it. You could only cast it if it were created as an Order or a subclass of Order.

    My guess is that whatever fetches the data from the database creates a Record when it could create an Order (and return it as a Record). Something like:

    public Record Fetch(int id)
    {
       // ... get data from db
    
       Record rec;
       if(data.Type = "Order")
          rec = new Order();
       else
          rec = new Record();
    
       return rec;
    }
    

提交回复
热议问题