Hi,
I have a base class (order) with a set of sub classes (productorder, specialorder, partsorder etc).
Only Some of these sub classes implement a particular interface (ITrackingCustomer) which has a single method declaration (object getcustdetails()).
As part of my solution all of my orders are processed in a central place, i.e. any crud methods pass through a central layer. Within this central layer I want to do the following:
If order is of type ITrackingCustomer
Then invoke method getcustdetails()
I have this working using the following code:
if (typeof(ITrackingCustomer).IsAssignableFrom(Order.GetType()))
{
MethodInfo theMethod = Order.GetType().GetMethod("getcustdetails");
object y = theMethod.Invoke(Order, null);
}
I am happy with the first part using isassignablefrom but would like to use a less performance intensive method for the second part (i.e. the reflection using invoke). My question is:
Is there a more efficient way of doing this as I have read that using the invoke command is costly.
Thanks
Steve
Loading
stevePosted Jan 29, 2010, 10:07 AM
For reference the code below does what I need:
ITrackingCustomer trackingCustomer = Order as ITrackingCustomer;
if (trackingCustomer != null)
{
var y = trackingCustomer.getcustdetails();
}
Thanks Again
stevePosted Jan 28, 2010, 1:43 PM
Thanks for the suggestion, unfortunately virtual methods will not work for me because:
1) I am already inheriting from a base class and so any additional implementation templates need to be specified as Interfaces
2) I Didn't add the additional complexity to the original question but this base class is using MS Entity framework and is system generated code, thus why I cannot simply add virtual methods to this base class, as soon as I rebuild the generated code gets overwritten again. Thus at present I use partial classes to specify the interface implementation, and I cannot change the base class, i.e. inherit from my own wrapper class.
So I need to say in essence:
for any instance of type order determine if they have the additional functionlity attached and if so then invoke.
The issue is that not all classes of type order need this functionlity (in fact only 5% do). This would then normally mean create a different base class, but as mentioned i cannot change this as is generated, and what i dont wnat to do is manually change the generated code file each time i rebuild.
But yes i see your point as if i could, i would simply override virtual methods.
Thanks for your help and you can see why I simplified the original question. In essense I cannot change the hierachy tree, so need to do the same sort of thing with interfaces, which my original code does, but as mentioned i don't really want to use this due to performance issues. The reason for the performance concern is that this code is exceuted everytime a user performs any crud operation.
I hope this makes sense.
Regards
steve
Sam HobbsPosted Jan 28, 2010, 12:39 PM