C#11添加了文件作用域类型功能:一个新的file修饰符,可以应用于任何类型定义以限制其只能在当前文件中使用。
这样,我们可以在一个项目中拥有多个同名的类。
通过下面的项目显示,该项目包含两个名为Answer的类。
文件File1.cs中
namespace ConsoleApp11 { file static class Answer { internal static string GetFileScopeScret() => "File1.cs"; } static class InternalClassFromFile1 { internal static string GetString() => Answer.GetFileScopeScret(); } }
文件File2.cs中
namespace ConsoleApp11 { file static class Answer { internal static string GetFileScopeScret() => "File2.cs"; } static class InternalClassFromFile2 { internal static string GetString() => Answer.GetFileScopeScret(); } }
调用这两个方法,可以正常输出
static void Main(string[] args) { Console.WriteLine(InternalClassFromFile1.GetString()); Console.WriteLine(InternalClassFromFile2.GetString()); }
