簡體   English   中英

如何在.net中的對象創建過程中添加鈎子

[英]how to add hook in object creation process in .net

我想在創建對象之前自定義對象的行為。 我想可能在對象構造函數中添加一些鈎子並進行更改可以有一個選擇。 在.net中有沒有辦法這樣做? 非常感謝提前!

編輯:

這是一個例子:

假設我們有一個類Kid,它使用Perform方法在課堂上獲得學分。

public class Kid
{
    public void Perform() { ... }
}

學校開展講座:

public class School
{
    public void Chemistry() {
        // The school have a good chemistry teacher, so every kid study well
        // Kid.Perform() is modified to reflect that 
        Kid tom = new Kid();
        tom.Perform();
    }

    public void Biology() {
        //This class is boring, everyone will nap in 5~10 min
        // Kid.Perform() use a random number to simulate how 
        //long this kid can hold it.
        Kid tom = new Kid(); tom.Perform();
        Kid jerry = new Kid(); jerry.Perform();
    }
}

我們希望每個孩子以同樣的方式表演,我不想要:

  1. 更改類Kid,因為它是從第三方工具生成的,並在其他地方廣泛使用。
  2. 使用繼承。

在您的情況下,您必須在調用構造函數后添加邏輯。 你可以編寫一個工廠方法來做到這一點; 更換new SpecialObject()MyExtendedSpecialObject.Create()應該不會太困難。

public static class MyExtendedSpecialObject
{
    public static SpecialObject Create()
    {
        var newObject = new SpecialObject();

        // Do something with newObject

        return newObject;
    }
}

您只需向對象的構造函數添加邏輯。 如果你指的是連接到內存分配等的過程,那么這在.NET中是不可用的。

public class MyClass
{
    public MyClass()
    {
        // Constructor logic here...
    }

    public MyClass(string name)
    {
         // Overloaded constructor logic here...
    }
}

您可以使用System.Activator來創建實例。 您還可以“掛鈎”激活器並執行檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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