将参数中的字段传递给外部方法调用是否违反Open/Closed原则?

Does passing a field in a parameter to an external method call violate the Open/Closed principle?

在下面的代码中,从 class Foo 传递私有成员 _field 作为外部方法参数 (Bar.DoSomething(_field)) 是否违反了 SOLID 编程中的 Open/Closed principle做法?

In object-oriented programming, the open/closed principle states "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification"; that is, such an entity can allow its behaviour to be extended without modifying its source code.

据我了解,实体应该对扩展开放,但对修改关闭。但是,在这种情况下,_fieldFoo的构造函数中设置了一次,并且是readonly将私有成员传递给外部方法的参数是否违反了Open/Closed原则或其他一些最佳实践?

  public class Foo
  {
    private readonly int _field;

    public Foo(int input)
    {
      _field = input;
    }

    private void FooDoSomething()
    {
      Bar.BarDoSomething(_field); //Breaking Open/Closed Principle?
    }
  }

  public static class Bar
  {
    public static void BarDoSomething(int input)
    {
      //Something happens
    }
  }

不,这不违反open/closed原则。从 Bar 的角度来看,input 不是属于 Foo 的内部字段。它只是一个整数。 Foo 的内部状态仍然隐藏在 class.

更进一步,除非你在传递参数时指定ref

Bar.BarDoSomething(ref _field);

Bar_field的值都修改不了。交互是单向的。 Foo 告诉 Bar 做某事。那挺好的。

澄清 - 即使使用 ref 并且 Bar 可以 修改对 [=37= 没有任何影响的值] 原则。但是,如果 Bar.DoSomething 的目的是 return 一个值,那么 return 是一个 int 的函数会更好而不是修改一个的方法。这样调用者可以获取值并决定是否要更新 _field.