简体   繁体   English

从其他对象调用该方法的方法

[英]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. 我的Example对象完全是伪对象,但是我想将此类用作基类,并在此基础上更花哨。

So e.DoSomething() should call method from eng.DoSomething() . 因此e.DoSomething()应该从eng.DoSomething()调用方法。 I can't use inheritance or pass Engine object to Example as argument. 我不能使用继承或将Engine对象传递给Example作为参数。

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. 现在您可以说e.DoSomething() ,它将通过调用getter然后调用返回的操作通过委托进行调用。

Using reflection we can do the method call with same type info. 使用反射,我们可以使用相同的类型信息进行方法调用。 But other types method is not possible. 但是其他类型的方法是不可能的。 I think so. 我认同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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