CodeGo.net>如何使派生类函数被执行?
作者:互联网
我们有一个基类:过滤器. DistrFilter和ReportFilter继承自Filter.
在另一个类FilterService.cs中,我们有两个函数可以接受这三种类类型. FilterService对Filter对象进行操作,但不会继承任何内容.
public class FilterService
{
public string GetDesc(List<T> filters) where T : Filter
{
if(filters.Count == 0) return String.Empty;
StringBuilder s = new StringBuilder("<ul>");
foreach (T f in filters)
s.AppendFormat("<li>{1}</li>", GetFilterText(f));
s.Append("</ul>");
return s.ToString();
}
public string GetFilterText(Filter f)
{
return "filter";
}
public string GetFilterText(DistrFilter f)
{
return "distr filter";
}
public string GetFilterText(ReportFilter f)
{
return "report filter";
}
}
public static void main(string[] args)
{
List<DistrFilter> distrFilters = new List<DistrFilters>();
distrFilters.Add(new DistrFilter());
distrFilters.Add(new DistrFilter());
distrFilters.Add(new DistrFilter());
FilterService fs = new FilterService();
Console.WriteLine(fs.GetDescription(distrFilters));
}
然后打印:
>过滤器
>过滤器
…
我如何获得打印它呢?
> Distr过滤器
> Distr过滤器
…
解决方法:
在Filter中将GetFilterText()实现为虚拟方法:
class Filter
{
// Can be converted into a property as well.
public virtual string GetFilterText { return "filter"; }
}
class DistrFilter : Filter
{
public override string GetFilterText { return "distr filter"; }
}
然后执行以下操作:
StringBuilder s = new StringBuilder("<ul>");
foreach (T f in filters)
s.AppendFormat("<li>{0}</li>", f.GetFilterText());
或者,如果您想将指定过滤器文本的注意与“过滤器”类分开,请使用双分派(访客模式).如果您可以具有不同类型的过滤器服务,则这很有用.这可以通过以下方式完成:
interface IServiceAcceptor
{
string Accept(FilterService service);
}
public class Filter : IServiceAcceptor
{
string IServiceAcceptor.Accept(FilterService service)
{
return service.GetFilterText(this);
}
}
public class DistrFilter : Filter, IServiceAcceptor
{
string IServiceAcceptor.Accept(FilterService service)
{
return service.GetFilterText(this);
}
}
public class ReportFilter : Filter, IServiceAcceptor
{
string IServiceAcceptor.Accept(FilterService service)
{
return service.GetFilterText(this);
}
}
然后为您服务:
public string GetDesc<T>(List<T> filters) where T : IServiceAcceptor
{
if(filters.Count == 0) return String.Empty;
var s = new StringBuilder("<ul>");
foreach (T f in filters)
s.AppendFormat("<li>{0}</li>", f.Accept(this));
s.Append("</ul>");
return s.ToString();
}
一些参考:Double dispatch,Visitor Pattern
标签:derived-class,inheritance,overloading,c 来源: https://codeday.me/bug/20191102/1989231.html