为什么我不能在使用静态导入时将扩展方法称为静态方法?
背景:
我有一个静态类,但静态方法不是扩展方法。 我决定将方法重构为扩展方法,并且不希望任何代码破坏,因为扩展方法可以像静态方法一样被调用。 但是,当静态导入用于保存扩展方法的静态类时,代码确实中断了。
例:
我有一个带有扩展方法和静态方法的静态类:
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 } } }
但是当我使用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** } } }
问题:为什么在使用静态导入时无法将扩展方法称为静态方法?
由于语言设计:
使用static使得在指定类型中声明的扩展方法可用于扩展方法查找。 但是,扩展方法的名称不会导入到代码中的非限定引用的范围中。
使用指令
上述就是C#学习教程:为什么我不能在使用静态导入时将扩展方法称为静态方法?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1014109.html