“基本抽象通用类在大多数情况下是不好的选择”。为什么? (或为什么不) [英] "Base abstract generic class is a bad choice in most situations." Why? (Or Why not)

查看:108
本文介绍了“基本抽象通用类在大多数情况下是不好的选择”。为什么? (或为什么不)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在评论中看到一个博客帖子:


在大多数情况下,基本抽象泛型类是一个糟糕的
选项


这是真的,如果不是为什么?



什么洞察力导致这个陈述?

解决方案

大多数情况是完全模糊的。通用抽象类(或接口)是一个坏主意 if ,这种类的后代之间唯一的共同祖先是System.Object(如此问题的其他评论者所指出的)。

$ b否则(如果你有一个有意义的共同祖先),如果你想重命名或专门化成员,这是一个好主意。考虑这个例子:

  //工作类的有意义的共同祖先。 
接口IWorker
{
对象DoWork();
}

//工作类实现的通用抽象基类。
abstract WorkerImpl< TResult> :IWorker
{
public abstract TResult DoWork();

对象IWorker.DoWork()
{
return DoWork(); //调用TResult DoWork();
}
}

//具体的工作类,专门处理小数。
class ComputationWorker:WorkerImpl< decimal>
{
override decimal DoWork()
{
decimal res;

//做冗长的东西...

return res;
}
}

在这个例子中, ()在抽象类中被重新定义,变得具体和专门在 ComputationWorker


I have just seen on the comment to a blog post:

Base abstract generic class is a bad choice in most situations

Is this true, if not why?

What insight(s) leads to this statement?

解决方案

"Most situations" is outrightly vague. A generic abstract class (or interface) is a bad idea if the only common ancestor between descendants of such class is System.Object (as noted by other commenters of this question).

Otherwise (as in, if you do have a meaningful common ancestor), it's a good idea if you want to "rename" or "specialize" members. Consider this example:

// Meaningful common ancestor for the working classes.
interface IWorker
{
   object DoWork();
}

// Generic abstract base class for working classes implementations.
abstract WorkerImpl<TResult> : IWorker
{
   public abstract TResult DoWork();

   object IWorker.DoWork()
   {
      return DoWork(); // calls TResult DoWork();
   }
}

// Concrete working class, specialized to deal with decimals.
class ComputationWorker : WorkerImpl<decimal>
{
    override decimal DoWork()
    {
       decimal res;

       // Do lengthy stuff...

       return res;
    }
}

In this example, DoWork() was redefined in the abstract class, becoming concrete and specialized in ComputationWorker.

这篇关于“基本抽象通用类在大多数情况下是不好的选择”。为什么? (或为什么不)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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