对象中的公共可变域

时间:2014-07-10 07:26:09

标签: f# c#-to-f#

是否可以在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()

2 个答案:

答案 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();