对象中的公共可变字段 [英] Public Mutable Field in Object

查看:79
本文介绍了对象中的公共可变字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在F#中创建一个简单的公共可变字段?我正在创建一个将从C#程序访问的库,我需要能够从C#设置一个字段。

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()


推荐答案

type MyObj() = 
    [<DefaultValue>]
    val mutable myVariable : int
    member this.SomeMethod() = 
        this.myVariable <- 10

您可以省去 [< DefaultValue>]] 如果没有主构造函数,但这可以处理更常见的情况。

You can leave off [<DefaultValue>] if there's no primary constructor, but this handles the more common case.

这篇关于对象中的公共可变字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆