Public Mutable Field in Object

拈花ヽ惹草 提交于 2019-12-24 05:32:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!