使用静态导入时,我为什么不能调用扩展方法为静态方法? [英] Why can't I call an extension method as a static method when using static import?

查看:174
本文介绍了使用静态导入时,我为什么不能调用扩展方法为静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:

我做了一个静态类,但静态方法是不是扩展方法。我决定重构方法为扩展方法,并没有想到任何代码打破,因为扩展方法可以这样调用静态方法。但是,代码没有突破时被用于静态类持有的扩展方法静态导入

I had a static class, but the static methods weren't extension methods. I decided to refactor the methods into extension methods and didn't expect any code to break since extension methods can be called like static methods. However, code did break when static import was used for the static class holding the extension methods.

示例:

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

I have a static class with an extension method and a static method:

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指令,一切都在测试程序工作正常以下内容:

When I use the following using directive, everything in the test program works fine:

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
            }
        }
    }




但是,当我使用的指令,以确定只是扩展方法的类使用静态导入,我不能调用扩展方法为静态方法:

But when I use the static import using directive to identify just the class with the extension method, I can't call the extension method as a static method:

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**
        }
    }
}


问:
使用静态导入时,我为什么不能调用扩展方法作为一个静态方法?

Question: Why can't I call an extension method as a static method when using a static import?

推荐答案

使用静态使得可用于扩展方法查找指定类型
宣布扩展方法。 然而,在
扩展方法的名称不导入范围在代码中不合格
的参考。

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

这篇关于使用静态导入时,我为什么不能调用扩展方法为静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆