Reputation: 2115
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?
Upvotes: 1
Views: 55
Reputation: 174
Using reflection we can do the method call with same type info. But other types method is not possible. I think so.
Upvotes: 0
Reputation: 62542
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.
Upvotes: 2