Is开发者_如何学Python it possible to have method have methods that are only callable externally and never callable internally? If so how?
Public Class Foo
Public Sub New()
Bar ' Should fail to compile as Bar is only accessible externally.'
End Class
Public External Sub Bar()
End Sub
End Class
No, that's not possible in C# or VB. Why would you want to do that anyway? Why would you "trust" the code within the class less than the code outside it?
Is it possible to have method have methods that are only callable externally and never callable internally? If so how?
No, this is not possible to stop at compile-time (you could walk the stack at run time, but that smells horrible).
Can you explain why you want this?
If you explicitly implement an interface, the implementation requires a cast; Doesn't sound like exactly what you want, but it may work in a pinch? But then, maybe it would be better to outline why you are asking for this, there probably is a better overall approach...
public class Foo : IBar
{
void IBar.Bar() {}
void AMethod() {
Bar(); // Compile Failure
((IBar)this).Bar(); // No failure
}
}
Note that this requires the code outside to also reference the object as an IBar, that may make it even less desirable as a solution for you. Sorry.
I don't think is possible in an easy way, generally is the other way round, you want to use something internally and prevent the consumers to call internal things. Internally, as the designer of the class, you know how things work and you do not need to be prevented to access certain methods.
the designer/coder of the class will probably have written the internal methods and the public ones as well so he/she will know what should not be called from inside... if it makes sense at all... if you have a good design I kind of doubt.
I'm curious why you would want to do this? Ever?
But no, in short, you cannot. YOU are the developer, so just make sure you never call it.
Now you COULD attempt force it to fail at run time:
public void MyExternalOnlyMethod(object sender)
{
if(sender==this) throw new ICantCallMeException();
}
Of course you then have to ensure your internal method calls to this method (which you shouldn't write to begin with) have to send "this" as sender...
But like the others said...
Why???
About as close as you'll ever get is using abstract methods, but that's just for requiring that a derived class implement certain functionality that you yourself wont in your class.
精彩评论