C#11添加了檔案作用域型別功能:一個新的file修飾符,可以應用于任何型別定義以限制其只能在當前檔案中使用,
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()); }
這里有幾點說明:
- 可以在其源檔案之外間接訪問帶有file修飾符的型別,在上面的程式中,我們依賴這些類,并從 InternalClassFromFile1 與 InternalClassFromFile2中訪問,
- file類也可以介面在其源檔案之外間接使用,演示如下
修改File.cs中代碼
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()); }
- 任何型別的型別都可以用file修飾符標記:class, interface , record , struct, enum, delegate.
- file不能與其他修飾符(如internal or public)一起使用,
- 只要所有型別定義屬于同一個檔案,就可以使用分部類,如下所示:
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"; } }
- 該 file修飾符不適用于嵌套在父型別中的型別,它也不適用于方法屬性、事件和欄位,但語言設計說明解釋說:“為非型別檔案范圍的成員留出設計空間,以便以后出現,”
- 在一個專案中,可以有一個internal級別類,同時可以用友一個或多個file級別的同名類,唯一的缺點是檔案類不能在公共類中使用,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/531872.html
標籤:.NET Core
上一篇:篇(3)-Asp.Net Core入門實戰-資料庫配置說明
下一篇:C#11 file關鍵字
