Cannot use protected events in F #

Say we have the following C # class

public class Class1 { protected event EventHandler ProtectedEvent; protected virtual void OverrideMe() { } } 

It seems impossible to use ProtectedEvent in F #.

 type HelpMe() as this = inherit Class1() do printfn "%A" this.ProtectedEvent member x.HookEvents() = printfn "%A" x.ProtectedEvent member private x.HookEvents2() = printfn "%A" x.ProtectedEvent override x.OverrideMe() = printfn "%A" x.ProtectedEvent 

In this example, I tried calling printfn on it, as there are several ways to hook events in F #, and I would like to be clear that this is just a reference to the event in general, which causes the problem.

In each of the above cases, the compiler complains of the following error:

A protected element is invoked or "base" is used. This is only allowed in the immediate implementation of members, since they can avoid the scope of the object.

I understand this mistake that causes her and her purpose. Usually the work around is to end the call in a private member that works great with methods - but this doesn't seem to work with events. No matter what I try to do, it is impossible to use protected events in F # unless I resort to something with reflection or make some changes to the base class (which is impossible in my case).

Note that I also tried all possible combinations of using base , this and x .

Am I doing something wrong?

+5
source share
1 answer

I suspect there is something about the code that the compiler creates behind the scenes when you view the event as a first-class value that later confuses it (i.e. some kind of hidden lambda function that makes the compiler think that it cannot access a protected member). I would say that this is a mistake.

As far as I can tell, you can get around this by using the add_ProtectedEvent and remove_ProtectedEvent members directly (they are not displayed in the autocompletion, but they are also available - they are protected, but the call is a direct method call, which is fine):

 type HelpMe() = inherit Class1() member x.HookEvents() = let eh = System.EventHandler(fun _ _ -> printfn "yay") x.add_ProtectedEvent(eh) override x.OverrideMe() = printfn "hello" 

This compiled for me. It's a shame that you cannot use a protected event as a first class value, but that at least allows you to use it ...

+3
source

Source: https://habr.com/ru/post/1210000/


All Articles