Eric Lippert 只是 blogged on this very topic。
它的基本要点是确保一个类可以“信任”受保护方法的调用者。共享一个公共基类的类——即使这个公共基定义了受保护的方法——在这方面本质上是陌生的。
Eric 的示例基于银行应用程序的概念。与其重现他的例子,我将在这里反刍:
// Good.dll:
public abstract class BankAccount
{
abstract protected void DoTransfer(
BankAccount destinationAccount,
User authorizedUser,
decimal amount);
}
public abstract class SecureBankAccount : BankAccount
{
protected readonly int accountNumber;
public SecureBankAccount(int accountNumber)
{
this.accountNumber = accountNumber;
}
public void Transfer(
BankAccount destinationAccount,
User authorizedUser,
decimal amount)
{
if (!Authorized(user, accountNumber)) throw something;
this.DoTransfer(destinationAccount, user, amount);
}
}
public sealed class SwissBankAccount : SecureBankAccount
{
public SwissBankAccount(int accountNumber) : base(accountNumber) {}
override protected void DoTransfer(
BankAccount destinationAccount,
User authorizedUser,
decimal amount)
{
// Code to transfer money from a Swiss bank account here.
// This code can assume that authorizedUser is authorized.
// We are guaranteed this because SwissBankAccount is sealed, and
// all callers must go through public version of Transfer from base
// class SecureBankAccount.
}
}
// Evil.exe:
class HostileBankAccount : BankAccount
{
override protected void Transfer(
BankAccount destinationAccount,
User authorizedUser,
decimal amount) { }
public static void Main()
{
User drEvil = new User("Dr. Evil");
BankAccount yours = new SwissBankAccount(1234567);
BankAccount mine = new SwissBankAccount(66666666);
yours.DoTransfer(mine, drEvil, 1000000.00m); // compilation error
// You don't have the right to access the protected member of
// SwissBankAccount just because you are in a
// type derived from BankAccount.
}
}
虽然您呈现的内容看起来很简单,但如果允许它发生,那么您在这里看到的那种恶作剧是可能的。现在您知道受保护的方法调用要么来自您的类型(您可以控制),要么来自您直接继承的类(您在编译时就知道)。如果它向从声明类型继承的任何人开放,那么您将永远无法确定知道可以调用受保护方法的类型。
当您将 BaseClass 变量初始化为您自己的类的实例时,编译器只会看到该变量的类型为 BaseClass,从而将您置于信任圈之外。编译器不会分析所有的赋值调用(或潜在的赋值调用)来确定它是否“安全”。