C# 应该模型 Class 成员是 Public 或私有

C# Should Model Class Members be Public or Private

大多数 C# class 成员是否应该在大多数情况下设置为私有,只有在我希望其他 classes 修改它们的情况下(然后我会让它们 public) ?我看到大多数教程都使所有 class 成员成为 public。我开始认为这可能是不好的做法。

想了解一般的软件工程原理。

https://github.com/Apress/pro-asp.net-core-mvc/blob/master/Source%20Code%201-31/08%20-%20SportsStore/SportsStore/src/SportsStore/Models/Product.cs

示例:

public class Product {
        public int ProductID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
        public string Category { get; set; }
    }

在应用程序的上下文中回答您的问题...

你的例子是模特1。它的属性是 public 因为:

By convention, public properties with a getter and a setter will be included in the model.2

一般来说,属性是 public(或受保护的,或内部的)并且字段是私有的。

A 属性 意味着以某种方式暴露。例如,模型公开了一些属性。

私有字段适合依赖。例如,在 ProductController3 中来自链接的 repo:

public class ProductController : Controller {
    private IProductRepository repository;
    // ...

    public ViewResult List(int page = 1) {
        // Use repository, only in ProductController
        // ...
    }
}

参考资料

  1. https://docs.microsoft.com/en-us/ef/core/modeling/
  2. https://docs.microsoft.com/en-us/ef/core/modeling/included-properties
  3. https://github.com/Apress/pro-asp.net-core-mvc/blob/ecbc7336cc9b4adb05825e8a0a355f3089fa4f0a/Source%20Code%201-31/08%20-%20SportsStore/SportsStore/src/SportsStore/Controllers/ProductController.cs

P.S。关于 "general software engineering principles" 的问题主要基于意见,因此有被关闭的风险。请参阅此 Stack Overflow 帮助主题:How do I ask a good question?