01.派生
using System;
using System.Collections.Generic;
using static System.Console;
namespace Inherit
{
class Program
{
static void Main(string[] args)
{
//子类可以隐式转换父类
Parent subclass=new Subclass();
Parent parent = subclass;
try
{
//父类不可以转换子类
Parent newParent = new Parent();
Subclass newSubclass = (Subclass)newParent;
Console.WriteLine(newSubclass.age);
}
catch (Exception e)
{
WriteLine(e);
}
ReadKey();
}
}
class Parent
{
public int hp { get; set; }
}
class Subclass:Parent
{
public int age { get; set; }
}
}
02.继承
using System;
using System.Collections.Generic;
using static System.Console;
namespace Inherit
{
class Program
{
static void Main(string[] args)
{
Contact contact=new Contact();
contact.Name = "1";
SubClass sub=new SubClass();
sub.Name = "Sub";
sub.Address = "192.168.01.01";
ReadKey();
}
}
class PdaItem
{
public string Name { get; set; }
public DateTime LastUpdate { get; set; }
}
class Contact:PdaItem
{
public string Address { get; set; }
public string Phone { get; set; }
}
class SubClass:Contact
{
}
}
类型转换
class Program
{
static void Main(string[] args)
{
SubClass sub = new SubClass();
sub.Name = "Sub";
sub.Address = "192.168.01.01";
PdaItem pdaItem = sub;//派生类sub 属于PdaItem类型 可以直接复制给PdaItem类型的变量 称为隐式转换
Console.WriteLine(pdaItem.Name); // "Sub"
PdaItem newPdaItem=new PdaItem();
SubClass newSub = (SubClass) newPdaItem; //显示转换
Console.WriteLine(newSub.Phone); //Phone不属于newSub对象实例 转换失败
ReadKey();
}
}
class PdaItem:Object
{
public string Name { get; set; }
public DateTime LastUpdate { get; set; }
}
class Contact:PdaItem
{
public string Address { get; set; }
public string Phone { get; set; }
}
class SubClass:Contact
{
}
static void Main(string[] args)
{
SubClass sub = new SubClass();
sub.Name = "Sub";
sub.Address = "192.168.01.01";
PdaItem pdaItem = sub;//派生类sub 属于PdaItem类型 可以直接复制给PdaItem类型的变量 称为隐式转换
Console.WriteLine(pdaItem.Name); // "Sub"
Console.WriteLine(sub.GetHashCode());
Console.WriteLine(pdaItem.GetHashCode());
ReadKey();
}
03.重写
04.抽象类
05.System.Object
06.is操作符