In C # can I set event limits?
Nope.
I want to limit the types that can subscribe to a specific event based on the interface that they implement.
Event listeners are instances of delegates of a type compatible with the type of event. "Types" are not event listeners.
those. I want the Employee object to implement IPerson to subscribe to the event handler, but another Truck object that implements a completely different interface, which should be limited.
The employee object does not listen to the event in the first place. The only thing that listens to the event is the delegate object.
You say you want to accept delegates who are delegates of methods that are instances of a method of a particular class? This is very strange, and I recommend not trying to do it .
It is impossible to prevent this at compile time, but if you really delve into this strange thing, you can do it at runtime.
To do this, like the other answers, you can create access methods for the adder and deletion for the event, and then put a check in the adder that checks that the delegate recipient matches the type that you approve, and throw an exception if it is not.
But again, this sounds like an unusually bad idea. It is up to the listener to decide whether they are interested in the event, and not to the source of the events, in order to check his listeners. Users have a reasonable expectation that any available event can be listened to by any delegate of a compatible type.
Perhaps you can explain why you want to do this strange thing; may be the best way to achieve your goal.
Eric Lippert
source share