西河刘卡车医 发表于 2022-11-12 08:56:24

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());
      }https://img2022.cnblogs.com/blog/1033233/202211/1033233-20221111175040550-599617323.png 这里有几点说明:

[*]可以在其源文件之外间接访问带有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仍然是避免类型名称冲突的首选方法。 
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: C#11 file关键字