【发布时间】:2015-08-03 13:35:39
【问题描述】:
我有一个基本抽象类来实现模板方法模式。
public abstract class OptionalParameter
{
//Template Method Pattern
public string GenerateQueryString()
{
return this.GenerateQueryStringWithParameters();
}
}
而且我有一个适用于所有 OptionalParameter 类型的扩展方法。
public static class OptionalParameterExtensions
{
public static string GenerateQueryStringWithParameters(this OptionalParameter optionalParameters)
{
}
}
我从 OptionalParameter 继承了一个名为 CalendarEventParameter 的类。
public class CalendarEventParameters : OptionalParameter
{
}
当我想创建CalenderEventParameter 的实例时,我在抽象类中看到GenerateQueryString() 方法和GenerateQueryStringWithParameters() 扩展方法。
我不想从派生类中看到它。我试图将扩展方法签名为私有,但这样我也无法从我的抽象类访问。
是否可以只从基抽象类调用扩展方法?
【问题讨论】:
-
为什么要隐藏扩展方法?或者更确切地说,您为什么首先将其声明为扩展方法?
-
扩展方法是编译器的东西。 Intellisense 使用 type 来确定它何时适用。由于继承,任何继承的类型都将显示其基类型扩展方法。从理论上讲,只要扩展名从列表中隐藏,就可以通过一些 VS 扩展名来定义(通过某些属性)来隐藏它。另请参阅this 问题,特别是 Jon 的想法(为扩展方法提供单独的命名空间)。
标签: c# inheritance extension-methods