背景:
我有一个静态类,但静态方法不是扩展方法。我决定将这些方法重构为扩展方法并且不希望任何代码中断,因为扩展方法可以像静态方法一样被调用。但是,当静态导入用于包含扩展方法的静态类时,代码确实中断了。
示例:
我有一个带有扩展方法和静态方法的静态类:
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.
关于c# - 为什么在使用静态导入时不能将扩展方法作为静态方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42715052/