问题描述
F#3.0为对 base
和 protected
成员的调用添加了更严格的检查。我有一些像C#中的抽象类,它有 protected static
辅助方法供派生类使用。
F# 3.0 adds stricter checks for calls to base
and protected
members. I have something like the following abstract class in C# that has protected static
helper methods to be used by derived classes.
public abstract class Processor {
public abstract void Process();
protected static void Helper(object arg) { }
}
,其中一个辅助方法作为第一类函数传递:
In F#, one of those helper methods is passed as a first-class function:
type DerivedProcessor() =
inherit Processor()
let init f =
f ()
override x.Process() =
init Processor.Helper
它在2.0中编译无投诉,但在3.0中会产生错误:
It compiles without complaint in 2.0, but in 3.0 produces an error:
好,在另一个静态成员中包装调用
OK, it's easy enough to comply, just wrap the call in another static member
static member private HelperWrapper(arg) = Processor.Helper(arg)
并传递该intead。但为什么?
and pass that intead. But why?
C#对这个模式没有问题。
C# has no problem with this same pattern.
public class HappyToCompile : Processor {
private void Init(Action<object> f) {
f(null);
}
public override void Process() {
Init(Helper);
}
}
问题: / p>
The questions:
- 为什么要添加更严格的支票?
推荐答案
使用我的心理语言设计技巧,我猜想F#2.0生成的是不可验证的代码。请参见发表在Eric Lippert的博客上,以解释C#中的相关问题(自C#4,IIRC后已修复)。
Using my psychic language design skills, I'd guess that F# 2.0 is generating unverifiable code. See this post on Eric Lippert's blog for an explanation of a related issue in C# (which has been fixed since C# 4, IIRC).
总之,创建一个F#函数,你真正创建一个新类派生自 FSharpFunc ,并从该类中调用您的protected方法是无效的,因为它不在
In short, when you create an F# function you are really creating a new class deriving from FSharpFunc<_,_>
, and calling your protected method from within that class isn't valid since it's not in the inheritance chain.
当然,不是不允许这些调用,编译器可以做你正在做的事情(创建一个私有方法并使用它),但也许这些好处被认为不会超过实施改进的成本。
Of course, rather than disallowing these calls, the compiler could just do what you're doing (create a private method and use that), but perhaps the benefits were thought not to outweigh the cost of implementing that improvement.
这篇关于了解F#3.0中对受保护/基本成员使用的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!