zl程序教程

您现在的位置是:首页 >  其他

当前栏目

C#11 file关键字

2023-02-18 16:34:13 时间

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仍然是避免类型名称冲突的首选方法。