gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:30:09 25 4
gpt4 key购买 nike

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

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/

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