为什么F#中没有受保护的访问修饰符? [英] Why isn't there a protected access modifier in F#?

查看:64
本文介绍了为什么F#中没有受保护的访问修饰符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a better way of modeling data in F# to avoid needing it?

推荐答案

在C#中,protected修饰符可能会引起很多问题,因为您经常需要从lambda表达式中调用成员.但是,这样做时,您不再从类内部访问该方法.使用C#中声明的受保护成员时,这也会引起混乱(例如,请参见此SO问题).如果可以声明protected成员,则以下代码可能会令人惊讶:

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

该代码将不起作用,因为您是从lambda函数(与Test的当前实例不同的对象)中调用Test的,所以该代码将不起作用.我认为这是不支持F#中的protected修饰符的主要原因.

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#.

在F#中,使用实现继承(即从基类继承)的频率通常比在C#中使用的频率要低得多,因此您不必经常使用protected.相反,通常最好使用接口(在面向对象的F#代码中)和高阶函数(在功能代码中).但是,很难说一般如何避免protected的需要(除了避免实现继承之外).您是否有一些激发问题的具体例子?

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?

这篇关于为什么F#中没有受保护的访问修饰符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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