【问题标题】:Why can't I call an extension method as a static method when using static import?使用静态导入时,为什么不能将扩展方法调用为静态方法?
【发布时间】:2016-12-23 09:59:18
【问题描述】:

背景:

我有一个静态类,但静态方法不是扩展方法。我决定将这些方法重构为扩展方法,并且不希望任何代码中断,因为扩展方法可以像静态方法一样被调用。但是,当静态导入用于包含扩展方法的静态类时,代码确实会中断。

示例:

我有一个带有扩展方法和静态方法的静态类:

namespace UsingStaticExtensionTest.Extensions
{
    static class ExtensionClass
    {
        internal static void Test1(this Program pg)
        {
            System.Console.WriteLine("OK");
        }

        internal static void Test2(Program pg)
        {
            System.Console.WriteLine("OK");
        }

    }
}

当我使用以下 using 指令时,测试程序中的一切正常:

using UsingStaticExtensionTest.Extensions;
namespace UsingStaticExtensionTest

    {
        class Program
        {
            static void Main(string[] args)
            {
                var p = new Program();
                ExtensionClass.Test1(p); // OK
                p.Test1(); // OK
                ExtensionClass.Test2(p); // OK
            }
        }
    }

但是当我使用静态导入 using 指令仅识别具有扩展方法的类时,我无法将扩展方法调用为静态方法:

using static UsingStaticExtensionTest.Extensions.ExtensionClass;
    class Program
    {
        static void Main(string[] args)
        {
            var p = new Program();
            //Test1(p); // Error: The name Test1 does not exist in the current context
            p.Test1(); // OK
            Test2(p); // OK **I can still call the static method**
        }
    }
}

问题: 使用静态导入时,为什么不能将扩展方法调用为静态方法?

【问题讨论】:

  • 可能是这里的语法处理的一个怪癖,扩展方法的语法需要一个表达式来调用扩展方法。换句话说,在一个类中你不能简单地做ExtensionMethod();;并暗示this.。看起来扩展方法的这种语法强制胜过静态导入。

标签: c# static extension-methods using


【解决方案1】:

因为语言设计:

使用静态使得扩展方法声明为指定类型 可用于扩展方法查找。 但是, 扩展方法不会导入到不合格的范围内 代码中的引用。

using Directive

【讨论】:

  • 不错的答案。任何人都知道这其中的原因吗?原则上这似乎违反直觉,但我可能会遗漏一些东西。
  • @IsaacLlopis 可以区分(对于扩展 [静态] 方法)不导入它们以供不合格的参考,但这可能更违反直觉,因为可能会失去给定的含义。喜欢void Substract(this Collection, Collection)。如果符合条件,我希望这两个中的哪一个是 minuend 而 Collection.Substract(Collection) 是显而易见的。最终没有人会使用不合格的方法。
猜你喜欢
  • 1970-01-01
  • 2011-03-02
  • 2011-11-16
  • 2013-03-12
  • 2011-01-24
  • 1970-01-01
  • 2011-12-11
  • 1970-01-01
相关资源
最近更新 更多