“受保护的” C# 中的方法?
在 C# 中将方法定义为受保护的有哪些好处?
like :
protected void KeyDemo_KeyPress( object sender, KeyPressEventArgs e )
{
// some code
}
与这样的东西相比:
private void FormName_Click( object sender, EventArgs e )
{
//some code
}
我在很多书中看到过这样的例子,但我不明白他们为什么以及何时使用 private
与 protected
?
What are the benefits to defining methods as protected
in C#?
like :
protected void KeyDemo_KeyPress( object sender, KeyPressEventArgs e )
{
// some code
}
As compared to something like this:
private void FormName_Click( object sender, EventArgs e )
{
//some code
}
I've seen such examples in many books and I don't understand why and when do they use private
vs protected
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
可以从派生类调用受保护的方法。 私有方法不能。
这是私有方法和受保护方法之间唯一的区别。
Protected methods can be called from derived classes. Private methods can't.
That's the one and only difference between private and protected methods.
当您想让子类覆盖其他“私有”方法时,通常会使用“受保护”。
因此,我们从继承中获得了我们所了解和喜爱的覆盖行为,而无需将InternalUtilityMethod暴露给我们类之外的任何人。
Often 'protected' is used when you want to have a child class override an otherwise 'private' method.
So we have the override behavior we know and love from inheritance, without unnecessarily exposing the InternalUtilityMethod to anyone outside our classes.
也请记住这一点:如果您有一个按钮和该按钮的 OnClick 设置为 Button_Click
,则 Button_Click 方法需要至少具有受保护的可见性才能由该按钮访问。
您可以通过在 Page_Load 方法中添加以下内容来解决此问题:
Keep this in mind too: If you have a button and that button's OnClick is set to Button_Click
then the Button_Click method needs to have at least protected visibility to be accessible by the button.
You could get around this by added the following to you Page_Load method:
.NET 的某些方面(例如 ASP.NET)会在运行时创建代码隐藏类的子类。 例如,ASP.NET Page 类继承自其代码隐藏类。 通过使该方法受保护,动态生成的页面类可以轻松地将按钮单击事件连接到处理该事件的基类中的受保护方法。
Some aspects of .NET such as ASP.NET create subclasses of your code-behind class at runtime. So an ASP.NET Page class for example inherits from its codebehind class. By making the method protected, the dynamically generated page class can easily hook up a button click event to a protected method in the base class that handles it.
如果您有一个继承的表单(或任何与此相关的类),您将能够从子类中调用此函数。
If you have an inherited form (or any class for that matter), you would be able to invoke this function from within the sub-class.
受保护的方法就像私有方法一样。 它们只能由班级成员访问。 唯一的区别是与私有成员不同,受保护的成员也可以由派生类访问。
Protected Methods are just like private methods. They could be accessed only by the members of the class. Only difference is unlike private members, protected members could be accessed by the derived classes as well.