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

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

问题描述

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

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

推荐答案

protected 修饰符在 F# 中可能很成问题,因为您经常需要从 lambda 表达式调用成员.但是,当您这样做时,您将不再从类中访问该方法.这也会在使用 C# 中声明的受保护成员时引起混淆(参见例如 this SO question).如果您可以声明一个 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天全站免登陆