简体   繁体   中英

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.

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

Try this

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

You could try and do the interface implementation as the Șhȇkhaṝ has above.

You could also use an abstract class if you require initial processing before class A or B's test method is invoked.

Here is an example of a console app 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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM