简体   繁体   中英

Method call that call method from other object

I was wondering if it's possible to otain such behaviour where method call of one object will call method of another object.

public class Example
{
    public void DoSomething() { /*BASICALLY NOTHING*/ }
}

public class Engine
{
    public void DoSomething() { Console.WriteLine("bleee"); }

    static void Main()
    {
        Example e = new Example();
        Engine eng = new Engine();

        e.DoSomething = eng.DoSomething;
    }
}

My Example object is exactly dummy object, but I would like to use this class as base class and build on top of it something more fancy.

So e.DoSomething() should call method from eng.DoSomething() . I can't use inheritance or pass Engine object to Example as argument.

Is it possible? How to achieve that? Is such approach used somewhere?

You can't do this in the way you describe, but you can do it with delegates.

public class Example
{
    public Action DoSomething {get; set;}
}

public class Engine
{
    public void DoSomething() { Console.WriteLine("bleee"); }

    static void Main()
    {
        Example e = new Example();
        Engine eng = new Engine();

        e.DoSomething = eng.DoSomething;
    }
}

Now you can say e.DoSomething() and it will call via the delegate by calling the getter and then calling the returned action.

Using reflection we can do the method call with same type info. But other types method is not possible. I think so.

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