将派生类转换为基类 [英] Convert derived class to base class

查看:76
本文介绍了将派生类转换为基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试刷新自己的记忆,但无法通过Google找到答案.

I'm trying to refresh my memory but can't find answers with Google.

public class BaseClass
{
    public virtual void DoSomething()
    {
        Trace.Write("base class");
    }
}

public class DerivedClass : BaseClass
{
    public override void DoSomething()
    {
        Trace.Write("derived class");
    }
}

如果创建派生类的实例,如何将其转换为基类,以便在调用DoSomething()时仅使用基类的方法?

If I create an instance of derived class, how do I convert it to it's base class so that when DoSomething() is called, it uses the base class's method only?

动态转换仍然调用派生类的重写方法:

A dynamic cast still calls the derived class's overridden method:

DerivedClass dc = new DerivedClass();

dc.DoSomething();

(dc as BaseClass).DoSomething();

输出:派生类"

推荐答案

您不能-完全是故意的,因为这就是多态性的全部内容.假设您有一个派生类,该类在传递给重写方法的参数上强制执行某些先决条件,以保持完整性……您不希望能够绕过该验证并破坏其内部完整性.

You can't - that's entirely deliberate, as that's what polymorphism is all about. Suppose you have a derived class which enforces certain preconditions on the arguments you pass to an overridden method, in order to maintain integrity... you don't want to be able to bypass that validation and corrupt its internal integrity.

在类本身内,您可以非虚拟地调用base.AnyMethod()(无论您要重写的方法是什么),但这没关系,因为这是类本身决定潜在地破坏其完整性的原因-大概它知道什么它正在做.

Within the class itself you can non-virtually call base.AnyMethod() (whether that's the method you're overriding or not) but that's okay because that's the class itself deciding to potentially allow its integrity to be violated - presumably it knows what it's doing.

这篇关于将派生类转换为基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆