C#: Is there way to ensure an object is only accessible through its events?
Is there a way to create some sort of interface that only allows the object to be acce开发者_如何学JAVAssible through events?
Can't you just define an interface with only events in it?
For instance:
interface IExample
{
event EventHandler Event1;
event EventHandler Event2;
}
class Obj : IExample
{
public event EventHandler Event1;
public event EventHandler Event2;
}
Usage:
IExample obj = new Obj();
obj.Event1 += Event1_Handler;
obj.Event2 += Event2_Handler;
Without further information, the best answer I have is that you would simply need to make sure that all of the members properties, functions, etc) are declared as private, except for the events, which would be public.
Although I have to admit, I'm stumped as to how this would eve be useful, and what would trigger a event if it's only accessible to it's events. It's like saying can you create a phone that you can't call, but can only hear the ring (the IncomingCall event).
A setup like this would expose only events to a client using the assembly:
interface ISomething {
event EventHandler MyEvent;
}
internal class MyClass : ISomething {
...
}
public ClassFactory {
public ISomething GetClass(){ // factory method
return new MyClass();
}
}
Or, if you need to restrict the use of this class in its own library as well you can do this:
public class MyClass : ISomething {
private MyClass(){} // private constructor
public ISomething GetClass(){ // factory method
return new MyClass();
}
}
Something like this may be combined with a singleton object if you just need to get its events as well, which can make sense if you simply want have a generic way to subscribe to that object's status events for example.
Be aware that any object to which a caller has access can have any of it's fields accessed through reflection.
If your question is focused on preventing people from accidentally invoking your object incorrectly, Matt B.'s answer is great.
If your question is focused on making it impossible for someone to maliciously access private fields of your object, that's not possible.
精彩评论