Determing type of DataTable event in C++
I am creating an inheritance model for event handling (particularly for DataTables
and XmlNode
).
I have a super class called EventManager
with the following virtual functions:
DataCha开发者_运维技巧nged(EventArgs *arg)
DataChanging(EventArgs *arg)
DataInserted(EventArgs *arg)
DataInserting(EventArgs *arg)
DataRemoved(EventArgs *arg)
DataRemoving(EventArgs *arg)
and also derived classes DataTableManager
and XmlNodeManager
.
DataTable
event arguments vary (e.g. DataRowChangeEventArgs
and DataColumnEventArgs
). If the event arg was casted to an EventArgs
for the parameter, how can I determine the original type once in the derived class, i.e. how can I know if the parameter passed was originally a DataRowChangeEventArgs
or a DataColumnEventArgs
?
Normally, you should invoke derived-class functionality using virtual functions. However, if you really must test for a type, do this:
DataRowChangeEventArgs* foo = dynamic_cast<DataRowChangeEventArgs*>(arg);
if (foo) {
// is a DataRowChangeEventArgs
}
Of course, you can also roll that into a single line:
if (DataRowChangeEventArgs* foo = dynamic_cast<DataRowChangeEventArgs*>(arg)) {
// is a DataRowChangeEventArgs
}
(If you've used C# at all, a dynamic_cast
on a pointer is pretty much like the as
operator in C#---it returns a pointer to the target type if appropriate, otherwise null.)
精彩评论