开发者

F# Shortcut Syntax for Properties?

For the normal property getter/setter syntax

let mutab开发者_StackOverflow社区le myInternalValue

member this.MyProperty 
    with get() = myInternalValue
    and set(value) = myInternalValue <- value

is there a shortcut, similar to the following in C#?

someType MyProperty { get; set; }

If there is one, I seem to be unable to find it...


F# 3 has auto-implemented properties so you can declare properties without declaring the backing field.

Example taken from Properties(F#) on MSDN:

type MyClass() =
    member val MyProperty = "" with get, set


There is no shortcut for creating get/set property in F#, but if you want a property with just get you can use the following simple syntax:

type Test(n) =
  let myValue = n * 2
  member x.Property = 
    // Evaluated each time you access property value
    myValue + 5

Since F# is a functional language, F# types are very often immutable. This syntax makes it very easy to define immutable types, so it also encourages you to use a good functional programming style in F#.

However, I agree that a shortcut for get/set property would be very useful, especially when writing some code that needs to interoperate with C# / other .NET libraries.

EDIT (5 years later...): This has been added in F# 3.0, as the answer from Ben shows :-)


is there a shortcut, similar to the following in C#?

I don't think so (nothing shown in "Expert F#"'s syntax summary), and the F# syntax is already quite brief compared to the full syntax needed in C#.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜