簡體   English   中英

C#Generics - 試圖找到模式的名稱

[英]C# Generics - trying to find the name of a pattern

我一直在嘗試在C#中找到泛型使用模式的名稱,我不知道比堆棧溢出更好的資源!

我正在做的是創建直接傳遞派生類的通用基類 - 我查看並查找了這個或模式名稱的示例,我希望這個社區的一位偉大成員可以幫助我。

我在http://www.mobiusbay.com/home/alittlesomethingimcallingcascadinggenerics上寫了一篇關於它如何工作的文章,但是如果你不想在那里閱讀它,那么它的一個例子如下:

public abstract class IndexedMemberBase<TDerivedClass> : IDisposable where 
    TDerivedClass : IndexedMemberBase<TDerivedClass>
{
    #region Declarations & Properties
    private static List<TDerivedClass> derivedInstances = new List<TDerivedClass>();
    public static List<TDerivedClass> DerivedInstances
    {
        get { return derivedInstances; }
    }
    #endregion

    #region Constructor(s)
    public IndexedMemberBase()
    {
        if (derivedInstances == null) derivedInstances = new List<TDerivedClass>();
        derivedInstances.Add((TDerivedClass)this);
    }
    #endregion

    #region Methods
    public void Dispose()
    {
        if (derivedInstances.Contains(this) == true)
        {
            derivedInstances.Remove((TDerivedClass)this);
        }
    }
    #endregion
}

這是基類,派生類可以非常簡單 - 例如:

public class IndexMember : IndexedMemberBase<IndexMember>
{
    //Add all the crazy business you could ever want!
}

這段代碼將指向dervied類的每個實例的指針拋出到靜態集合中以供一般使用 - 該集合對於每個派生類都是不同的,因此您不會在基礎中靜態存在沖突。 我發現它在我的項目中非常有用,我希望其他人可以找到它的用途。

需要指出的重要一點是,派生類將自己的通用簽名傳遞給基類。

如果有人看到這種模式在使用中,或者知道它的名字 - 我真的很想看到一些例子,或者至少用它的正確名稱來稱呼它! 現在,我稱之為遞歸泛型,因為它似乎合適,但我確信有一個更好的名字!

非常感謝您的幫助!

亞當

它被稱為奇怪的重復模板模式

(由於某種原因,它在SO上才非常出名?)

Eric Lippert在他的博客中寫過這篇文章

它被稱為奇怪的重復模板模式,雖然它指的是C ++,它們是模板而不是泛型

暫無
暫無

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

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