I've seen similar questions/answers for this posted in the past, but mine differs slightly from the others that I've seen.
Essentially, I have a common interface and several classes that implement/inherit from it. Then, in a separate class, I have methods that must act upon objects given by the interface IObject. However, each of them must be acted upon in different ways, hence why there is a separate declaration of the method for each concrete type that extends IObject.
class IObject
{
...
}
class ObjectType1 : IObject
{
...
}
class ObjectType2 : IObject
{
...
}
class FooBar
{
void Foo (ObjectType1 obj);
void Foo (ObjectType2 obj);
}
Now, to me, one obvious solution is to take advantage of dynamic binding by placing the method Foo inside each individual class, which would automatically choose at runtime the correct Foo to execute. However, this is not an option here, because I am defining multiple models for how to act upon these objects, and I would rather encapsulate each individual model for handling objects in its own class, rather than stuff all of the models into the object classes.
I found this post which shows how to use a dictionary to dynamically choose at runtime the correct method implementation. I'm fine with this approach; however, suppose that I have to perform a dispatch like this once in every model. If I only have IObject and its concrete implementations, is there any way to generalize this approach so that I could call methods of any name based on the runtime type of the objects?
I know this is probably an unclear question, but I would greatly appreciate any help.
The dynamic
keyword is actually really good at this:
void Main()
{
var foobar = new FooBar();
foreach(IObject obj in new IObject[]{ new ObjectType1(), new ObjectType2()})
{
foobar.Foo((dynamic)obj);
}
// Output:
// Type 1
// Type 2
}
class IObject
{
}
class ObjectType1 : IObject
{
}
class ObjectType2 : IObject
{
}
class FooBar
{
public void Foo (ObjectType1 obj) {
Console.WriteLine("Type 1");
}
public void Foo (ObjectType2 obj) {
Console.WriteLine("Type 2");
}
}
The code is super-simple, and it's got pretty decent performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With