c# - 我找到了一个依赖于在其扩展中定义的方法的类。这是一种模式吗?

标签 c# design-patterns scope extension-methods compile-time

我找到了一个看起来像这样的类:

using System;
// no using statement that brings either IMyClass or
// MyClassExtensions into scope

namespace Org.Foo {

    class MyClass {

    public void QuizzicalMethod(IMyClass thingy,
                                string stringToPass) {
        thingy.ExtensionMethod(StringToPass);
    }
}

在代码库的 IMyClass.cs 中有一个 IMyClass 接口(interface)定义(在相同的命名空间和目录中),但它不包含 QuizzicalMethod 的定义。相反,MyClassExtensions.cs 具有:

using System;
namespace Org.Foo {
    public static class MyClassExtensions {
        public static void ExtensionMethod (this IMyClass self,
                                            string stringToPass) {
            // Do some stuff
        }
    }
}

因此,当 MyClass 被定义时,MyClassExtensions 显然超出了范围,因此当 QuizzicalMethod 使用 IMyClassExtensions 时。 ExtensionMethod——已定义。在我看来,QuizzicalMethod 定义的参数列表及其对 thingy.ExtensionMethod 的调用都应该中断。 (让我想知道测试中是否存在代码覆盖问题。)这导致了一些问题:

  • 如何编译而不出错?
  • 为什么类作者甚至想将 QuizzicalMethod 带出类定义并将其放入扩展中?
  • 这是否符合现有的命名模式?
  • 是否存在某种范围界定异常或后期绑定(bind)?如果是这样,它如何不破坏 C# 中的所有其他内容?

提前致谢!

编辑:修正了一些拼写错误。

最佳答案

Thus, MyClassExtensions is clearly out of scope when MyClass is defined

不,MyClassExtensionsMyClass 都在同一个命名空间中声明。您不需要 using 指令来调用同一命名空间或封闭命名空间中的扩展方法。

您还没有解释 IMyClass 的声明位置,所以我无法对此发表评论。

来自 C# 5 规范的第 7.6.5.2 节(谈论寻找包含扩展方法的类 C):

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:
  • 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.
  • 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.

基本上,这只是一种扩展方法。在不了解更多真实 上下文的情况下,我们无法评论为什么这是一个扩展方法而不是 IMyClass 上的方法。

关于c# - 我找到了一个依赖于在其扩展中定义的方法的类。这是一种模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24170330/

相关文章:

design-patterns - 惯用的元编程

java - 需要提取一个接口(interface),但是实现上多了一个方法

javascript - javascript 是否将(默认情况下)未声明的变量声明到当前本地作用域(基于首次使用)而不是全局作用域?

c# - Grpc.授权 : Could not load type 'Grpc.Core.CallCredentials' from assembly 'Grpc.Core.Api'

c# - 通过 MAPI 接口(interface)从 MailItem 获取电子邮件文件夹

java - 速度分析器 - 基于参数类型的抽象方法或开关

php - 是否可以在 PHP 中访问外部局部变量?

javascript - JavaScript 回调的效率

c# - Xml Serializer 中的注释问题

c# - 无法在我的代码中使用 Hwndsource