Passing an object to an object from a derived class

I have a class Recordthat works fine:

public class Record 
{
    protected string table;
    protected string idcolumn;
    public Record(string _table, string _idcol, int _id) 
    {
        table = _table;
        idcolumn = _idcol;
        Id = _id;
    }
}

I also have a class Orderthat is derived from Recordthat implements additional methods that apply only to a specific type of record:

class Order : Record 
{
    public void Start() 
    {
    }
}

In my application, I have an object of the theRecordtype Recordthat I want to pass in Orderso that I can call the method Starton it.

I tried to do this:

Order r = (Order)theRecord;

but throws it away InvalidCastException.

I think that I could create a new constructor for Orderwhich accepts Record, but I already have an object (which is created by retrieving the record from the database).

How could I implement this correctly?

+1
4

, ( ). - , - .

Record record = new Record();
Order order = (Order)record;//wont work since record is some record not an Order

, -

Record record = new Order();

Order order = (Order)record;//works since record is Order
+4

InvalidCastException, theRecord Order, . , Order Order.

, , , Record, Order ( Record). - :

public Record Fetch(int id)
{
   // ... get data from db

   Record rec;
   if(data.Type = "Order")
      rec = new Order();
   else
      rec = new Record();

   return rec;
}
+5

is as, , - , , :

Record objectToHoldCastedObject;
if(theRecord is Order)
{
    objectToHoldCastedObject = theRecord as Order;
}

is , .

as , , null .

: as , ; is , . , is , as , .

0

, , . , , Record, Order. , (XmlSerializer, JavaScriptSerializer, JSON.NET ..).

, / ( , ). , Record, Order.

0

Source: https://habr.com/ru/post/1540093/


All Articles