c# - 为什么在使用静态导入时不能将扩展方法作为静态方法调用?

标签 c# static extension-methods 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");
        }

    }
}

当我使用以下 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**
        }
    }
}

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

最佳答案

由于语言设计:

Using static makes extension methods declared in the specified type available for extension method lookup. However, the names of the extension methods are not imported into scope for unqualified reference in code.

using Directive

关于c# - 为什么在使用静态导入时不能将扩展方法作为静态方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42715052/

相关文章:

.net - 为什么我需要这个。在母版页中使用扩展方法的限定符?

c# - 文件返回时出现 InvalidOperationException

c# - AdalSilentTokenAcquisitionException : Failed to acquire token silently as no token was found in the cache. 调用方法 AcquireToken

c# - VS2022配置Azure keyvault看不到本地secrets.json

c# - 为什么我的静态类没有在 ASP.NET MVC 中初始化?

ios - "Any?"类的 Swift3 扩展?

c# - ThreadPool.QueueUserWorkItem——是否需要新的 WaitCallback()?

java - 当对象的引用是静态的时,如何访问对象中的非静态方法?

properties - 如何从 typescript 中的静态函数访问非静态属性

c# - 如何为此创建扩展方法/lambda 函数