-3
public class Base
{
    public virtual void SomeOtherMethod()
    {
    }
}


public class Derived : Base
{
    public new void SomeOtherMethod1()
    {
    }
}

**Base b = new Derived();

Derived d = new Derived();

Derived d=new Base();**

我无法理解上面这三行的对象实例化?在派生类的情况下,我对如何实例化对象的概念有些困惑。有人可以帮助我了解这些概念吗?

混淆了等号的左右部分?

4

1 回答 1

1

改变这个:

public new void SomeOtherMethod1()

...和:

public override void SomeOtherMethod1()

那就是如果您想要实际的多态性(更改基成员的实现)。

关于其他线路

这被称为upcast。由于Derivedis 类型Base因为它继承Base,所以可以将更具体的实例向上转换为不太具体的引用:

Base b = new Derived()

另一条线是垂头丧气的。出于与upcast相同的原因,您可以向下转换实例并将其存储在更具体的类型化引用中,如果更具体派生出更具体的引用。

问题是,在你的情况下,Base永远不会是 type Derived,因为Base不继承Derived。但你可以做下一个沮丧

Base base = new Derived(); // This is an upcast again
Derived derived = (Derived)base; // Using an explicit downcast to Derived! 
于 2013-03-01T13:55:10.880 回答