[英]Method call that call method from other 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;
}
}
我的Example
对象完全是伪对象,但是我想将此类用作基类,并在此基础上更花哨。
因此e.DoSomething()
应该从eng.DoSomething()
调用方法。 我不能使用继承或将Engine
对象传递给Example
作为参数。
可能吗? 如何实现呢? 是否在某处使用了这种方法?
您无法以描述的方式执行此操作,但是可以使用委托进行操作。
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;
}
}
现在您可以说e.DoSomething()
,它将通过调用getter然后调用返回的操作通过委托进行调用。
使用反射,我们可以使用相同的类型信息进行方法调用。 但是其他类型的方法是不可能的。 我认同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.