问题
Is it possible to create a simple public mutable field in F#? I'm creating a library that I will be accessing from a C# program and I need to be able to set a field from 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()
回答1:
type MyObj() =
[<DefaultValue>]
val mutable myVariable : int
member this.SomeMethod() =
this.myVariable <- 10
You can leave off [<DefaultValue>]
if there's no primary constructor, but this handles the more common case.
回答2:
How about:
[<CLIMutable>]
type MyObj =
{ mutable myVariable : int }
member x.SomeMethod() =
x.myVariable <- x.myVariable + 10
Then you can do:
var obj = new MyObj();
obj.myVariable = 5;
obj.SomeMethod();
or
var obj = new MyObj(5);
obj.SomeMethod();
来源:https://stackoverflow.com/questions/24670719/public-mutable-field-in-object