Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a class method using another class instance?

I have a requirement of dynamically invoke a class and use the methods of that class.

public class A
{
  public void test()
  {
  }
}

public Class B
{
  public void test()
  {
  }
}
class object intermediate
{
//here will decide which class to be invoked
//return the invoked class instance
}

class clientclass
{
intermedidate client=new intermediate();
}

So can i access the methods of the invoked class, in the instance client. Im using Framework 3.5. If child class inherited from the intermediate class, is it possible to achieve this? I dont want reflection here.


1 Answers

You can do like follows (not verified)

interface I
{
}
class A :I
{
}

Class B:I
{
}
class intermediate
{
    public I GetInstance(int i)
    {
        if(i==1)
           return new A();
        else
            return new B(); 
    }

}
class clientclass
{
      I client=new intermediate().GetInstance(1);
}
like image 187
शेखर Avatar answered Jun 27 '26 19:06

शेखर



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!