Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

two class with common methods and properties [duplicate]

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

like image 209
Admdebian Avatar asked Dec 16 '15 08:12

Admdebian


2 Answers

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");
}
like image 192
Hamid Pourjam Avatar answered Sep 18 '22 12:09

Hamid Pourjam


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();
}
like image 25
Domysee Avatar answered Sep 18 '22 12:09

Domysee