簡體   English   中英

從其他對象調用該方法的方法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM