using System;
using System.Collections.Generic;
using System.Text;namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//test1 example = new test1();
test2 example2 = new test2();
test1 example1 = example2;
example1.printfStringA();
example1.printfStringB();
example2.printfStringA();
example2.printfStringB();
}
}
}class test1
{
public void printfStringA()
{
Console.WriteLine("A");
}
public virtual void printfStringB()
{
Console.WriteLine("B");
}
}class test2:test1
{
public new void printfStringA()
{
Console.WriteLine("C");
}
public override void printfStringB()
{
Console.WriteLine("D");
}
}
在这个程序中 test2 example2 = new test2();
test1 example1 = example2;
但是不能 test1 example1 = new test1();
test2 example2= example1;
是什么原因
谢谢
using System.Collections.Generic;
using System.Text;namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//test1 example = new test1();
test2 example2 = new test2();
test1 example1 = example2;
example1.printfStringA();
example1.printfStringB();
example2.printfStringA();
example2.printfStringB();
}
}
}class test1
{
public void printfStringA()
{
Console.WriteLine("A");
}
public virtual void printfStringB()
{
Console.WriteLine("B");
}
}class test2:test1
{
public new void printfStringA()
{
Console.WriteLine("C");
}
public override void printfStringB()
{
Console.WriteLine("D");
}
}
在这个程序中 test2 example2 = new test2();
test1 example1 = example2;
但是不能 test1 example1 = new test1();
test2 example2= example1;
是什么原因
谢谢
解决方案 »
- Ajax问题
- 请问SHELLDLL_DefView是干什么的?
- 键盘钩子 C#
- C# treeview key的问题
- 如何把带有索引像素的图片黑白化
- 如何实现把一个窗口中的值传到另一个窗口!windowsform中
- Mysql 更新innodb 类型的表 :出现Lock wait timeout exceeded; try restarting transaction
- 如何使用ActiveX控件AxMSChart?
- SqlDataReader问题,是不是一个conn只能由一个SqlDataReader用呀
- Convert.ToInt32所有人不会注意的问题
- zip的原理是什么?
- 未与信任 SQL Server 连接相关联
test1 example1 = example2; // 子类型可以隐式转换成基类型
但是不能 test1 example1 = new test1();
test2 example2= example1; // 基类型不可以隐式转换成子类型
// 可以写成这样 test2 example2= (test2)example1; 但这种转换是不安全的
子类继承自父类,那么一般来说,父类能用的方法,对子类也同样适用。但子类中定义的方法父类就不能用了。test1 example1 = example2;
说明白点儿,example1是父类创建的对象,所以对父类能执行的方法,对他都可以执行,所以,允许他以一个子类来初始化,毕竟你要用到example1时,调的都是父类的方法。而test2 example2 = example1;
example2是子类的对象,执行时调用的是子类中的方法,而example1中是不一定包含这些方法的,所以不允许这样来赋值。
楼主 某楼主 = new 楼主();
人 某人 = 某楼主;//因为“某楼主”肯定是个“人”,所以可以赋值
但不能
人 某人 = new 人();
楼主 某楼主 = 某人;//因为“某人”有可能不是“楼主”,所以不能赋值
当父类想要向下转型时,需要首先知道那个父类是子类,然后才可以向下转型为子类的。
就像上面这个例子,改成:
test1 example1 = new test2();//example1虽然是父类,但是他实际上是用子类赋值的,所以他也可以看成子类,所以可以向下转型成功
test2 example2 = (test2)example1;