簡體   English   中英

如何從C#中的靜態方法引用當前類的類型

[英]How to refer to the type of the current class from a static method in C#

近年來,我一直在嘗試尋找這個問題的答案,但是我總是最終通過解決方法將其掃地出門,通過通過參數傳遞類型來引用類類型。

我的項目是一個類庫,實際上不應該允許這樣做,因為這些類負責至關重要的數據庫完整性,並且用戶有時會通過簡單地傳遞錯誤的類型來嚴重弄亂事情。 我知道,有很多方法可以通過運行時檢查來減少這種情況(這種情況),但這仍然會引起重復出現的問題,我想通過適當的解決方案一勞永逸地消除它。

基本上,我要尋找的是類的this關鍵字或typeof(this)表達式的等效項,而不是其instance

這是一個演示此問題的示例:

public abstract class Base
{
    protected static void InitializeTaggedFields(Type aType)
    {
        ...
    }
}

// User defined custom class inheriting my Base class
public class StoreThis : Base
{
    [Tag("something")]
    string Field1;
    [Tag("something")]
    string Field2;
    [Tag("something_else")]
    string Field3;

    // This constructor should be in the Base class because user has
    // to pass the type of his current class each time to initialize
    // the class.
    public StoreThis()
    {
        InitializeTaggedFields(typeof(StoreThis));
    }
}

非常感謝您的任何建議。

恐怕不可能-那是一件好事。

原因很簡單,在OOP中,基類不應該使用派生類固有的信息。

除非我完全誤解了所有內容,否則您想要的只是以下內容:

public abstract class Base
{
    protected static void InitializeTaggedFields(Type aType)
    {
        // aType will be of the instantiated type:
        // When a "StoreThis" is instantiated,
        // aType.Equals(typeof(StoreThis)) is true,
        // if a "StoreThat" was instatiated
        // aType.Equals(typeof(StoreThat)) is true.
        // etc, etc.
    }

    public Base()
    {
        InitializeTaggedFields(this.GetType());
    }
}

// User defined custom class inheriting my Base class
public class StoreThis : Base
{
    public StoreThis()
    {
    }
}

public class StoreThat : Base
{
    public StoreThat()
    {
    }
}

而且,您可能想將InitializeTaggedFields設為私有,因為它沒有在其他地方使用。

盡管我不熟悉您的情況,但您可以看一下工廠方法模式 您可以讓工廠根據類類型填寫帶標簽的字段。

暫無
暫無

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

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