Is it possible for an object to have access to the private field / function of another object of the same class?

I know this is possible in C #, which creates simple and efficient code. --- Two objects of the same class can access other private parts.

class c1 { private int A; public void test(c1 c) { cA = 5; } } 

But in F # this seems impossible, is this true?

 type c1() let A = 0 member test (c: c1) = cA 
+6
source share
5 answers

Interest Ask. It seems to work with an explicit field, but not with let binding:

 // Works type c1 = val private A : int new(a) = { A = a } member m.test(c : c1) = cA let someC1 = new c1(1) let someMoreC1 = new c1(42); let theAnswer = someC1.test someMoreC1 // Doesn't work type c2() = let mutable A = 42 // Compiler error: The field, constructor or member 'A' is not defined member m.test(c : c2) = cA 
+5
source

Yes, but in your example, A not a semantically private member of c1 , it is more like a local constructor variable.

@afrischke gives an example of how to define c1 with the actual private member A (using the val fields).

+2
source

You just use a directly in the instance method

 type c1() let A = 0 member x.test = A 

For the static method, this does not work, since the bindings of the bindings are slightly different - then you need a class definition, for example

 type c1() private member xA = 0 static member test (A:c1) = AA 
+1
source

In section 8.6.1 .3 of the states of the F # specification:

The functions and values ​​defined by the definitions of instances are lexically limited (and therefore implicitly private) to the object being defined.

+1
source

This is possible and widely used, for example, to test equality equally:

 type c1 = member private this.A = 0 interface IEquatable<c1> with member this.Equals (that: c1) = this.A = that.A // of course, it can be done in a regular method as well member this.Equals (that: c1) = this.A = that.A 
+1
source

Source: https://habr.com/ru/post/925306/


All Articles