Kei*_*thS 9 c# generics design-patterns
//this class (or interface if you like) is set up as generic...
public abstract class GenericBase<T>
{
public T PerformBasicTask(T in) { ... }
}
//... but is intended to be inherited by objects that close the generic...
public class ConcreteForDates:GenericBase<DateTime>
{
public DateTime PerformSpecificTask(DateTime in) { ... }
}
//... so that consuming code never knows that a generic is involved
var myDateConcrete = new ConcreteForDates(); //look ma, no GTP!
//These two methods look alike, and there is no generic type inference,
//even with PerformBasicTask().
var basicResult = myDateConcrete.PerformBasicTask(DateTime.Now);
var specificResult = myDateConcrete.PerformSpecificTask(DateTime.Today);
//does not compile because T is understood by inheritance to be a DateTime,
//even though PerformBasicTask()'s implementation may well handle an int.
var anotherBasicResult = myDateConcrete.PerformBasicTask(1);
Run Code Online (Sandbox Code Playgroud)
我已经多次看到并使用过这种模式,它对于在一系列特定类型的子类中提供通用功能非常有用.例如,这可以是控制器/演示者的模型,该控制器/演示者特定于一种域对象,该对象是该类用于控制的页面的核心; 检索/持久性等基本操作可能使用100%的常用功能,但绑定/解除绑定可能非常具体.
这种泛型声明模式是否有名称,而不会将通用暴露给最终用户?
| 归档时间: |
|
| 查看次数: |
331 次 |
| 最近记录: |