• C#11 file关键字


    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());
            }
     
    这里有几点说明:
    • 可以在其源文件之外间接访问带有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级别的同名类。唯一的缺点是文件类不能在公共类中使用。
     
    让我们强调一下,namespace仍然是避免类型名称冲突的首选方法。
     

    C#/.net/.net core QQ群:953553560


                    
  • 相关阅读:
    pytest框架之fixture测试夹具详解
    DAY17-深度学习100例-卷积神经网络(CNN)识别眼睛状态
    高考志愿选专业,如何分析自己的兴趣爱好?
    嵌入式学习笔记(47)Nand的常见操作及流程分析
    vite+vue3 + ts 项目搭建——pinia
    【vue设计与实现】异步组件与函数式组件 2 - 超时与Error组件
    Python【查重】
    深入浅出nginx
    SpringBoot 整合定时任务 Quartz、SpringBoot 内置定时任务 Task 代码详解
    我也来一个“羊了个羊”
  • 原文地址:https://www.cnblogs.com/chenyishi/p/16881352.html