Fork me on GitHub

『 再看.NET7』新的访问修饰符——file

  访问修符,是OOP中一个很重要的知识点。在C#中,class(类)的访问修饰符有public和internal两种。

  类成员(属性,方法,字段,事件等)的访问修饰符public,internal,protected,private,internal protected,protected private六种。

  .NET7到来时,C#11中添加了file访问修饰符。对,就是文件的意思,file是只能用来定义类型的访问修饰符,不能定义类型中的类成员,即使嵌套类也不可以。file是用来定义使用范围最小的类型访问修饰符,只限于在当前文件中,其他类型的成员内访问。

  file基本的使用场景是,当需要一个类型时,但又不想这个类型的使用范围延伸到外部,所以就在当前.cs文件定义一个file访问修饰符的类型,仅限于当前文件中的类型成员内部封装并访问。

  描述的有点绕,还是看一个例子吧,下面是在Product.cs文件中定义如下:

public class Product
{
    public string? Name { get; set; }
    public decimal PurchasePrice { get; set; }
    public void PrintSalesProduct()
    {
        var salesPrice = new SalesPrice
        {
            RetailPrice = PurchasePrice * 1.5m,
            WholesalePrice = PurchasePrice * 1.2m
        };
        Console.WriteLine($"Name:{Name},{salesPrice}");
    }
}
file record SalesPrice
{
    public decimal RetailPrice { get; set; }
    public decimal WholesalePrice { get; set; }
}   

  使用的时候如下:

var product = new Product();
product.Name = "冰棍";
product.PurchasePrice = 1;
product.PrintSalesProduct();

  输出结果:

  想要更快更方便的了解相关知识,可以关注微信公众号 

 

 

posted @ 2023-02-11 15:16  桂素伟  阅读(73)  评论(0编辑  收藏  举报