She*_*rif 18 .net c# oop access-modifiers visual-studio
如protected在C#中定义方法有什么好处?
喜欢 :
protected void KeyDemo_KeyPress( object sender, KeyPressEventArgs e )
{
// some code
}
Run Code Online (Sandbox Code Playgroud)
与这样的事情相比:
private void FormName_Click( object sender, EventArgs e )
{
//some code
}
Run Code Online (Sandbox Code Playgroud)
我在很多书中看过这样的例子,我不明白为什么以及何时使用privatevs protected?
Phi*_*ert 81
可以从派生类调用受保护的方法.私人方法不能.
这是私有方法和受保护方法之间唯一的区别.
当你想让一个子类重写一个"私有"方法时,通常使用'protected'.
public class Base {
public void Api() {
InternalUtilityMethod();
}
protected virtual void InternalUtilityMethod() {
Console.WriteLine("do Base work");
}
}
public class Derived : Base {
protected override void InternalUtilityMethod() {
Console.WriteLine("do Derived work");
}
}
Run Code Online (Sandbox Code Playgroud)
因此,我们拥有我们所知道并且喜欢继承的覆盖行为,而不必将InternalUtilityMethod暴露给我们类之外的任何人.
var b = new Base();
b.Api(); // returns "do Base work"
var d = new Derived();
d.Api(); // returns "do Derived work"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25125 次 |
| 最近记录: |