简体   繁体   中英

Why isn't there a protected access modifier in F#?

是否有更好的方法在F#中建模数据以避免需要它?

The protected modifier can be quite problematic in F#, because you often need to call members from a lambda expression. However, when you do that, you no longer access the method from within the class. This also causes confusion when using protected members declared in C# (see for example this SO question ). If you could declare a protected member, the following code could be surprising:

type Base() = 
  protected member x.Test(a) = a > 10

type Inherited() = 
  inherit Base()
  member x.Filter(list) =
    list |> List.filter (fun a -> x.Test(a))

This code wouldn't work, because you're calling Test from a lambda function (which is a different object than the current instance of Test ), so the code wouldn't work. I think this is tha main reason for not supporting the protected modifier in F#.

In F# you typically use implementation inheritance (that is, inheriting from a base class) much less frequently than in C#, so you shouldn't need protected as often. Instead, it is usually preferred to use interfaces (in the object-oriented F# code) and higher-order functions (in the functional code). However, it is difficult to say how to avoid the need for protected in general (other than by avoiding implementation inheritance). Do you have some specific example which motivated your question?

As to whether F# enables a better way of modeling data, signature files allow finer grained visibility decisions than internal does in C#, which is often very nice. See Brian's comment here for a little bit more explanation. This is independent of support (or lack thereof) for protected , though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM