为什么我不能在使用静态导入时将扩展方法称为静态方法?

ast*_*003 8 c# extension-methods static using

背景:

我有一个静态类,但静态方法不是扩展方法.我决定将方法重构为扩展方法,并且不希望任何代码破坏,因为扩展方法可以像静态方法一样被调用.但是,当静态导入用于保存扩展方法的静态类时,代码确实中断了.

例:

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

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");
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

当我使用以下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
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是当我使用static import 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**
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题: 为什么在使用静态导入时无法将扩展方法称为静态方法?

Ham*_*yan 8

由于语言设计:

使用static使得在指定类型中声明的扩展方法可用于扩展方法查找.但是,扩展方法的名称不会导入到代码中的非限定引用的范围中.

使用指令

  • 好答案。有人知道原因吗?原则上看似反直觉,但我可能会遗漏一些东西。 (2认同)