c# - 调用方法并直接读取/设置参数的私有(private)字段是否会破坏封装?

标签 c# class oop

考虑以下代码:

public class Counter
{
    private int _value;

    // public int Value => _value;
    // commented for asking purposes

    public void Increment() {
        _value++;
    }

    public void Decrement() {
        _value--;
    }

    public void CopyOtherCounter(Counter other)
    {
        _value = other._value;
        // the compiler didn't show any error here
        // why it does not break encapsulation?
    }
}

我想问一下这是否意味着破坏封装。

编辑:因为我认为我不应该能够读取其他对象私有(private)值,即使它具有相同的类型。因为这可能会发生:

public class Person {
    private float _walletMoney; // no getter
    private void StealFrom(Person other) {
        _walletMoney += other._walletMoney; //reading other private wallet
        other._walletMoney = 0; //writing other private wallet
    }
}

void Main() {
    var John = new Person();
    var Bob = new Person();
    John.StealFrom(Bob);
}

最佳答案

Encapsulation (computer programming)

In object-oriented programming (OOP), encapsulation refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object's components

根据定义,它仍然是封装的,位于类型内,并且具有非常具体的可访问性域!

简单地说,您可以访问定义它的类型中的私有(private)字段,这还包括嵌套的类型/(甚至如果您正在处理对类型的引用),本身(并由规范定义)是允许的。

要获取这方面的具体文档,您确实必须深入研究 C# 规范 which you can find here

以下是重要部分

8.5.2 Declared accessibility

...

  • Private, which is selected by including a private modifier in the member declaration. The intuitive meaning of private is “access limited to the containing type

更多

8.5.3 Accessibility domains

...

The accessibility domain of a nested member M declared in a type T within a program P, is defined as follows (noting that M itself might possibly be a type):

...

  • If the declared accessibility of M is private, the accessibility domain of M is the program text of T.

...

  • Otherwise, if M is private, the access is permitted if it occurs within the type in which M is declared.
  • Otherwise, the type or member is inaccessible, and a compile-time error occurs.

因此,即使能够在方法中访问私有(private)成员(当您只能访问一个引用),它本身仍然封装(尽管您可能会反对这个定义),并且可访问

关于c# - 调用方法并直接读取/设置参数的私有(private)字段是否会破坏封装?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60201447/

相关文章:

c# - 管理从 web api 返回的 json 中的属性名称

c# - xUnit 不等待异步测试

python - python 中 try 和 except 的使用

PHP:从类构造函数返回一个数组

java - OO设计和循环依赖

c# - 两个 BST 叶子之间的节点之和

c# - C++文本文件读取性能

c++ - 有没有办法调用模板参数类的未知方法?

c++ - 什么是已删除函数,为什么只有我传递文件的函数才被视为已删除?

c++ - 对象初始化后在C++中显示char数组时出现异常行为