I have two classes.
Class A:
class A() {
public void QQ() {}
public void WW() {}
}
And Class B:
class B() {
public void QQ() {}
public void WW() {}
}
They don't share the same interface or abstract class. A and B have two distinct hierarcy and I can't change that at the moment.
I want to write a single procedute that works for A and B and use QQ and WW methods.
Can I do that? Can you suggest any document I can study?
Tanks
This is called Duck Typing.
You can use dynamics
void Foo(dynamic dy)
{
dy.QQ();
}
You can also use reflection. (reference)
public static void CallQQ(object o)
{
var qq = o.GetType().GetMethod("QQ");
if (qq != null)
qq.Invoke(o, new object[] { });
else
throw new InvalidOperationException("method not found");
}
You can check if the object is of the specific type, then cast it and invoke its method:
void InvokeQQ(object o){
if(o is A)
(o as A).QQ();
if(o is B)
(o as B).QQ();
}
In C#6 you can simplify this to
void InvokeQQ(object o){
(o as A)?.QQ();
(o as B)?.QQ();
}
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