让一个类作为一个参数传递给一个通用基类的邪恶? [英] Is letting a class pass itself as a parameter to a generic base class evil?

查看:144
本文介绍了让一个类作为一个参数传递给一个通用基类的邪恶?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次看到一个同事在实现对象池时执行此操作。他将要作为参数汇总的类传递给通用基类。这个基类编排了池代码。



奇怪的是,基类会知道它的子代。在所有正常情况下,这被认为是不好的做法。但是在这种情况下,父母只是一个技术解决方案,以避免编写重复的代码。基类从不引用任何其他代码。



这种结构的一个缺点是它烧基础。您不能在层次结构中引入通用基类。



以下是一个可以想象的例子:

  public abstract class Singleton< T>其中T:class 
{
public static T Instance {get;私人集合

public Singleton()
{
if(Instance!= null)
抛出新异常(Singleton实例已创建);
实例=(T)(对象)this;
}
}

public class MyClass:Singleton< MyClass>
{
}

改进的代码:

  public abstract class Singleton< T>其中T:Singleton T 
{
public static T Instance {get;私人集合

public Singleton()
{
if(Instance!= null)
抛出新异常(Singleton实例已创建);
实例=(T)这个;
}
}

public class MyClass:Singleton< MyClass>
{
}


解决方案

否;这是一个众所周知的模式,称为 CRTP

特别是有用的C ++作为虚拟方法的替代。



您可以在.net框架内看到它在 IComparable< T> IEquatable< T>



为了增加稳健性,您应该添加 T:Singleton< T>


I first saw a colleague do this when he implemented object pools. He passed the class that was going to be pooled as a parameter to a generic base class. This base class layed out the pooling code.

The odd thing is that the base class will know of its children. This is considered bad practice in every normal case. But in this case the parent is just a technical solution to avoid writing repetetive code. The base class is never referenced by any other code.

One drawback with this construction is that it "burns the base class". You cannot introduce the generic base class in the middle of a hierarchy. This problem might be outside the topic.

Below is a thinkable example:

public abstract class Singleton<T> where T : class
{
    public static T Instance { get; private set; }

    public Singleton()
    {
        if (Instance != null)
            throw new Exception("Singleton instance already created.");
        Instance = (T) (object) this;
    }
}

public class MyClass : Singleton<MyClass>
{
}

Improved code:

public abstract class Singleton<T> where T : Singleton<T>
{
    public static T Instance { get; private set; }

    public Singleton()
    {
        if (Instance != null)
            throw new Exception("Singleton instance already created.");
        Instance = (T) this;
    }
}

public class MyClass : Singleton<MyClass>
{
}

解决方案

No; this is a well-known pattern called the CRTP.
It is especially useful in C++ as an alternative to virtual methods.

You can see it inside the .Net framework in IComparable<T> and IEquatable<T>.

For added robustness, you should add where T : Singleton<T>

这篇关于让一个类作为一个参数传递给一个通用基类的邪恶?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆