在C#中,如果未将类或方法标记为密封的或虚的,那是什么? [英] In C#, if a class or a method is not marked as sealed or virtual, what is it?

查看:34
本文介绍了在C#中,如果未将类或方法标记为密封的或虚的,那是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

换句话说,默认值是什么(如果未指定任何内容)?我猜默认值是虚拟的,因为即使没有指定虚拟方法,也可以使用"new"关键字来覆盖基本方法.如果是这样,那为什么我们甚至需要虚拟选项?当我们需要阻止进一步的继承时,我们是否只能使用Sealed?

In other words, what's the default (if nothing is specified)? I'm guessing the default is virtual, because you can use the "new" keyword to override a base method even when the base method has no virtual specified. If that's the case then why do we even need a Virtual option? Couldn't we just use Sealed when we do need to prevent further inheritance?

推荐答案

默认情况下,C#方法是密封的-如果没有 virtual 关键字,则无法覆盖它们.

C# methods are sealed by default -- you cannot override them without the virtual keyword.

new 关键字隐藏基类中的方法.

The new keyword hides the method in the base class.

这就是我隐藏的意思:

public class HidingA
{
    public string Get()
    {
        return "A";
    }
}

public class HidingB : HidingA
{
    public new string Get()
    {
        return "B";
    }
}

HidingA a = new HidingA();
HidingB b = new HidingB();

Console.WriteLine(a.Get()); // "A"
Console.WriteLine(b.Get()); // "B"

HidingA c = new HidingB();
Console.WriteLine(c.Get()); // "A". Since we're calling this instance of "B" an "A",    
                            //we're using the "A" implementation.

现在,虚拟版本!

public class VirtualA
{
    public virtual string Get()
    {
        return "A";
    }
}

public class VirtualB : VirtualA
{
    public override string Get()
    {
        return "B";
    }
}
VirtualA a = new VirtualA();
VirtualB b = new VirtualB();

Console.WriteLine(a.Get()); // "A"
Console.WriteLine(b.Get()); // "B"

VirtualA c = new VirtualB();
Console.WriteLine(c.Get()); // "B". We overrode VirtualB.Get, so it's using the 
                            // "B" implementation of the method

因此,如果我们采用以 HidingA 作为参数并将其传递为 HidingB 的实例的方法,我们将获得 HidingA Get 方法的实现.

So if we make a method that takes HidingA as a parameter and pass it an instance of a HidingB, we're going to get the HidingA implementation of the Get method.

MSDN: http://msdn.microsoft.com/zh-cn/library/6fawty39.aspx

除非指定 sealed 关键字,否则打开类进行继承.

Classes are open for inheritance unless the sealed keyword is specified.

这篇关于在C#中,如果未将类或方法标记为密封的或虚的,那是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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