gpt4 book ai didi

c# - 在扩展类型中访问扩展方法?

转载 作者:太空宇宙 更新时间:2023-11-03 22:37:21 25 4
gpt4 key购买 nike

我最近一直在重构一些旧代码,很多方法都可以用作基本类型的扩展方法,例如 doublefloatintstring 等。然而,当我一路走来取得很大进步时,我想到了一个想法。有多种方法可以访问扩展方法。让我们创建一个名为 Extensions 的容器类并添加一个基本的扩展方法(首先),以及一个我们将调用 Dummy 的虚拟类,该类使用一个简单的方法利用我们的扩展方法调用DoIt.

public static class Extensions {
public static double ToRadians(this double degrees) => degrees * Math.PI / 180.0;
}
public class Dummy {
public void DoIt() {
double radians = Extensions.ToRadians(45.0);
double degrees = 90.0;
radians = degrees.ToRadians();
}
}

这不是最优雅的示例,但它演示了广为人知的扩展方法访问。现在让我们为我们的 Dummy 类创建一个名为 WasteOfTime 的愚蠢且毫无意义的扩展,但在 Extensions 类中。

我不确定你为什么要这样做,但为了这个问题,让我们开始吧!

public static class Extensions {
...
public static void WasteOfTime(this Dummy dummy) { }
...
}

好吧,现在我们有了这个应该放在 Dummy 类中的完美小方法。好吧,由于扩展方法对类型的实例有效,您应该能够从 Dummy 类的名为 DoIt 的特殊方法调用 WasteOfTime

public void DoIt() {
...
WasteOfTime();
...
}

哦,等等,你不能那样做!找不到方法!让我们用 this 关键字来限定它吧!

this.WasteOfTime();

更好,它可以编译!有用!这是浪费时间!酷!


重要提示

不会考虑实际这样做,但出于好奇我试了一下。如果您能举一个有效的例子说明为什么这是一个好主意,请随时分享,但我相信这是其中之一; 您在想什么 实现类型。


问题

既然现代编译器不再需要使用 this 关键字来限定字段、属性和方法,为什么我必须限定扩展方法?

我唯一能想到的是扩展方法在技术上对基类是静态的。

最佳答案

首先,我会注意到在this 上调用扩展方法是有充分理由的。例如,您可能正在编写一个集合类并希望在其中使用 LINQ。没有错。现在,就问题而言:

Why did I have to qualify the extension method since modern compilers remove the need for qualifying fields, properties, and methods with the this keyword?

这不是编译器现代性的问题——而是关于语言规范的内容。来自 ECMA-334 , 第 12.7.6.3 节:

In a method invocation (§12.6.6.2) of one of the forms

expr . identifier ( )
expr . identifier ( args )
expr . identifier < typeargs > ( )
expr . identifier < typeargs > ( args )

if the normal processing of the invocation finds no applicable methods, an attempt is made to process the construct as an extension method invocation. If expr or any of the args has compile-time type dynamic, extension methods will not apply.

Method() 形式的方法调用不是其中一种形式,因为没有expr

所以编译器只是遵守规范的规则。至于为什么这样设计,那略有不同。我不知道这方面的细节(虽然我可以看到它们是否在规范的注释版本之一中)但我怀疑 Foo() 可以引用一个事实当前类或任何基类中的实例方法或静态方法使整个事情变得有点棘手。 (从 C# 6 开始,它也可以是 using static 指令导入的任何方法中的静态方法,注意...)

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

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