C#11新增了檔案作用域型別功能:一個新的file
修飾符,可以應用於任何型別定義以限制其只能在當前檔案中使用。
namespace ConsoleApp11 { file static class Answer { internal static string GetFileScopeScret() => "File1.cs"; } static class InternalClassFromFile1 { internal static string GetString() => Answer.GetFileScopeScret(); } }
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()); }
namespace ConsoleApp11 { file class Answer : IAnswer { public string GetFileScopeSecret() => "File1.cs"; } internal interface IAnswer { string GetFileScopeSecret(); } static class InternalClassFromFile1 { internal static IAnswer GetAnswer() => new Answer(); } }
static void Main(string[] args) { Console.WriteLine(InternalClassFromFile1.GetAnswer().GetFileScopeSecret()); }
namespace ConsoleApp1 { file static partial class Answer { internal static string GetFileScopeSecret() => "Answer from File1.cs"; } file static partial class Answer { internal static string AnotherGetFileScopeSecret() => "Another Answer from File1.cs"; } }