gpt4 book ai didi

c# - 扩展方法的继承

转载 作者:太空狗 更新时间:2023-10-29 21:44:33 24 4
gpt4 key购买 nike

继承如何与 C# 中的扩展方法一起工作。

假设您有一个接口(interface) IAIB : IAIC,以及一个类 Foo : IB, IC,现在一个定义扩展方法:

public static class Extensions {

public static void Bar (this IA instance) {
//Some code
}

public static void Bar (this IB instance) {
//Some code
}

public static void Bar (this IC instance) {
//Some code
}

public static void Bar (this Foo instance) {
//Some code
}

}

编译器如何确定 Foo.Bar() 的行为?根据经验测试,编译器总是选择最具体的实例(如普通调用)并且不使用动态绑定(bind)(因为 this 注释)是更“语法”的糖我想……

如果两个或多个类从继承层次结构中的不同分支定义一个方法,则调用是不明确的。在这种情况下,有没有一种方法可以定义一种方法相对于另一种方法的优先级?

以上说法正确吗?

最佳答案

继承确实很重要,但更重要的实际上是命名空间,来自 C# 规范:

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

可以在C# spec, 7.6.5.2 Extension method invocations 中找到确切的过程和示例。解析过程(其中C是可能的类型解析集,M是扩展方法集):

The search for C proceeds as follows:
• Starting with the closest enclosing namespace declaration, continuing with each enclosing namespace declaration, and ending with the containing compilation unit, successive attempts are made to find a candidate set of extension methods:

o If the given namespace or compilation unit directly contains non-generic type declarations Ci with eligible extension methods Mj, then the set of those extension methods is the candidate set.

o If namespaces imported by using namespace directives in the given namespace or compilation unit directly contain non-generic type declarations Ci with eligible extension methods Mj, then the set of those extension methods is the candidate set.

• If no candidate set is found in any enclosing namespace declaration or compilation unit, a compile-time error occurs.

• Otherwise, overload resolution is applied to the candidate set as described in (§7.5.3). If no single best method is found, a compile-time error occurs.

• C is the type within which the best method is declared as an extension method. Using C as a target, the method call is then processed as a static method invocation (§7.5.4).

如果我理解正确的话,这意味着它会在编译时选择最近命名空间中的最佳扩展方法。理解没有进行动态调用非常重要,解析是静态完成的(即在编译时)。

关于c# - 扩展方法的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24816350/

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