gpt4 book ai didi

c# - 为什么扩展方法表现不同?

转载 作者:太空狗 更新时间:2023-10-29 21:34:20 26 4
gpt4 key购买 nike

派生类包含一个“Count”方法,它对“Derived”类执行一些操作。另一方面,我有一个扩展方法,它也以“Derived”类为目标。

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();
}
}

最佳答案

规范 (§7.6.5.2) 明确指出实例方法优先于扩展方法:

if the normal processing of the invocation finds no applicable methods, an attempt is made to process the construct as an extension method invocation.

...

The preceding rules mean that instance methods take precedence over extension methods, that extension methods available in inner namespace declarations take precedence over extension methods available in outer namespace declarations, and that extension methods declared directly in a namespace take precedence over extension methods imported into that same namespace with a using namespace directive. For example:

如果实例方法与传递的参数相匹配,则甚至不会考虑扩展方法。

关于c# - 为什么扩展方法表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18175730/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com