派生类包含一个“计数”方法,该方法对“派生”类执行一些操作。另一方面,我有一个扩展方法,它也针对“派生”类。
Derived derived = new Derived();
derived.Count();
通过调用上面的代码片段将在派生类中执行“Count”方法。为什么 C# 编译器在这种情况下不发出警告并识别扩展方法。框架如何在内部处理这个?
//Base class
public class Base
{
public virtual string Count()
{
return string.Empty;
}
}
//Derived class
public class Derived : Base
{
public override string Count()
{
return base.Count();
}
}
//Extension Methods for Derived class
public static class ExtensionMethods
{
public static Derived Count(this Derived value)
{
return new Derived();
}
}