我知道这在 C# 中是可能的,它产生简单而高效的代码。--- 同一类的两个对象可以访问彼此的私有部分。
class c1
{
private int A;
public void test(c1 c)
{
c.A = 5;
}
}
但这在 F# 中似乎是不可能的,是真的吗?
type c1()
let A = 0
member test (c: c1) = c.A
我知道这在 C# 中是可能的,它产生简单而高效的代码。--- 同一类的两个对象可以访问彼此的私有部分。
class c1
{
private int A;
public void test(c1 c)
{
c.A = 5;
}
}
但这在 F# 中似乎是不可能的,是真的吗?
type c1()
let A = 0
member test (c: c1) = c.A
Interesting question. It seems to work with an explicit field but not with a let binding:
// Works
type c1 =
val private A : int
new(a) = { A = a }
member m.test(c : c1) = c.A
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) = c.A
是的,但是在您的示例中,它在A
语义上不是 的私有成员c1
,它更像是构造函数的局部变量。
@afrischke 提供了一个示例,说明如何c1
使用实际的私有成员A
(使用val
字段)进行定义。
这是可能的,并且被广泛使用,例如,用于检查成员相等性:
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
正如 F# 规范的第8.6.1 .3 节所述:
实例定义定义的函数和值在词法范围内(因此隐式私有)到正在定义的对象。
您只需a
在实例方法中直接 使用
type c1()
let A = 0
member x.test = A
对于静态方法,这不起作用,因为 let 绑定略有不同 - 然后您需要一个类定义,例如
type c1()
private member x.A = 0
static member test (A:c1) = A.A