Accessing a class method using an instance of another class?

I have a requirement to dynamically call 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 called class, on the client instance . I'm using Framework 3.5. If the child class inherits from an intermediate class, can this be achieved? I don't want to speculate here.

+3


source to share


3 answers


try it



public interface IClassA
{
    void Method();
}

public class ClassA : IClassA
{
    public void Method()
    {

    }
}

public static class ObjectInjector
{
    public static T GetObject<T>()
    {
        object objReturn = null;
        if(typeof(T) == typeof(IClassA))
        {
            objReturn = new ClassA();
        }
        return (T)objReturn;
    }        
}

public class ClientClass
{
    static void Main(string[] args)
    {
          IClassA objA = ObjectInjector.GetObject<IClassA>();
          objA.Method();
    }
}

      

0


source


You can do as follows (not tested)



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);
}

      

+4


source


You can try and follow the interface implementation as Şhȇkhaṝ has the above.

You can also use an abstract class if you need some initial processing before calling a method on class A or B.

Here's a sample console application that demonstrates this:

public abstract class MainClass
{
    public virtual void test()
    {
        Console.WriteLine("This is the abstract class");
    }
}

public class A : MainClass
{
    public override void test()
    {
        base.test();
        Console.WriteLine("Class A");
    }
}

public class B : MainClass
{
    public override void test()
    {
        base.test();
        Console.WriteLine("Class B");
    }
}

public class Intermediate
{
    public MainClass CreateInstance(string name)
    {
        if (name.ToUpper() == "A")
        {
            return new A();
        }
        else
        {
            return new B();
        };
    }
}

class Program
{
    static void Main(string[] args)
    {
        Intermediate intermediate = new Intermediate();
        var client = intermediate.CreateInstance("B");

        client.test();
        Console.ReadLine();
    }
}

      

0


source







All Articles