是否可以在F#中创建一个简单的公共可变字段?我正在创建一个我将从C#程序访问的库,我需要能够从C#中设置一个字段。
//C# Equivalent
public class MyObj
{
public int myVariable;
}
//F#
type MyObj =
//my variable here
member SomeMethod() =
myVariable <- 10
//C# Usage
MyObj obj = new MyObj();
obj.myVariable = 5;
obj.SomeMethod()
答案 0 :(得分:3)
type MyObj() =
[<DefaultValue>]
val mutable myVariable : int
member this.SomeMethod() =
this.myVariable <- 10
如果没有主要构造函数,您可以不使用[<DefaultValue>]
,但这会处理更常见的情况。
答案 1 :(得分:2)
怎么样:
[<CLIMutable>]
type MyObj =
{ mutable myVariable : int }
member x.SomeMethod() =
x.myVariable <- x.myVariable + 10
然后你可以这样做:
var obj = new MyObj();
obj.myVariable = 5;
obj.SomeMethod();
或
var obj = new MyObj(5);
obj.SomeMethod();