5

C#11 file关键字 - chester·chen

 1 year ago
source link: https://www.cnblogs.com/chenyishi/p/16881352.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

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

o_220321084757_%E5%85%AC%E4%BC%97%E5%8F%B7.png

                

o_220321084403_%E8%A7%86%E9%A2%91%E8%AF%BE%E7%A8%8B.png

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK