[英]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上才非常出名?)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.