17

我正在阅读有关制作自定义主体的教程,并且遇到了代码:

public class BaseController : Controller
{
    protected virtual new UserPrincipal User
    {
        get { return HttpContext.User as UserPrincipal; }
    }
}

“受保护的虚拟新”究竟是如何工作的?

关键词“新”是最让我困惑的。

4

3 回答 3

39

protected意味着它只在这个类和从它派生的类中可见。

virtual意味着它可以在派生类中被覆盖。

new意味着在这里您创建了新的覆盖层次结构,即您停止覆盖基类中定义的方法并用此方法替换它。

更多细节可以在这里找到

于 2012-09-30T14:44:17.923 回答
7

new用于成员隐藏。

与重写方法不同,new方法不会通过对基类的引用来调用。

请参阅文档

于 2012-09-30T14:43:58.283 回答
5

你的关键问题: “关键字new是最让我困惑的。”

简短的回答: new并且override是相互排斥的。new用于替换从基类继承的类成员。相反,override用于扩展基类实现的一个成员。

从新的修饰符(C# 参考) (Visual Studio 2013)

It is an error to use both new and override on the same member, because the two modifiers have mutually exclusive meanings. The new modifier creates a new member with the same name and causes the original member to become hidden. The override modifier extends the implementation for an inherited member.

于 2014-07-02T14:23:36.217 回答