3

在 Unity3D 中,我们可以通过将字段标记为公共来使其在编辑器中可访问。然后,这允许在 GUI 中分配字段的变量,而不是对其进行硬编码。例如,此 C# 代码将显示一个可以在开发过程中手动编辑的“速度”字段。如果保持不变,它将默认为 10:

public class Example : MonoBehaviour {
    public float speed = 10.0F; 
}

我尝试在 F# 中使用自动属性执行此操作:

type Example() =
    inherit MonoBehaviour()
    member val speed = 10.f with get,set 

但这不起作用。但是,如果我使用显式属性,它确实有效

[<DefaultValue>] val mutable speed : float32

但这具有无法在同一表达式中指定默认值的缺点。

显式和自动属性不是编译成同一件事吗,唯一的区别是显式属性总是初始化为零?以及如何在 F# 中声明等效的 C# 代码?

4

3 回答 3

4

我认为您混淆了两个不同的概念:显式字段和自动属性。在底层,属性更像是一个方法而不是一个字段,尽管访问/赋值在语法上是相似的。您的 C# 的 F# 等效项是:

type Example() as this =
  [<DefaultValue>] val mutable public speed: float32;
  do this.speed <- 10.0f
于 2013-11-07T20:03:28.757 回答
4

I think you are playing a little loosely with the terms "field" and "property".

The Unity editor doesn't bind properties automatically, and the first example you've provided is F#'s auto-properties. For the record, you couldn't bind the following C# in Unity editor pane either:

// does not bind in editor either
class Example : MonoBehavior { 
    public float speed { get; set; }
}

You have to use the code with [DefaultValue] and just initalize it in the constructor or alternatively have a let-bound private field that is tagged [SerializeField] and write your own property wrapper:

type Example () = 
    [<SerializeField>]
    let mutable _speed = 10f
    member this.speed 
        with get () = _speed 
        and set val = _speed <- val
于 2013-11-07T20:05:17.663 回答
1

另一种实现这一点的方法,它避免了[<DefaultValue>]命令式初始化,如下所示(注意第一行没有默认构造函数):

type Example =
    val mutable public speed : float32
    new() = { speed = 10.0f }
于 2013-11-09T17:52:16.547 回答