C#入门--多态(二)

C#入门--多态(二)

一.简单工厂设计模式(核心:根据用户的输入创建对象赋值给父类

namespace demo{ 
   class Test 
   { 
	   static void Main(String [] args) 
	   { 
			Console.WriteLine("请输入您需要的笔记本品牌:");
			string brand = Console.ReadLine();
			NoteBook nb = GetNoteBook(brand);
			nb.SayHello();
			Console.ReadKey();
	   } 
	   //简单工厂的核心:根据用户的输入创建对象赋值给父类
	   public static NoteBook GetNoteBook(string brand)
	   {
		   NoteBook nb = null;
		   //对品牌多条件定值判断
		   switch(brand)
		   {
			   case "Lenovo":nb = new Lenovo();
					break;
			   case "Acer":nb = new Acer();
					break;
			   case "Dell":nb = new Dell();
					break;
		   }
		   return nb;
	   }
   } 
   
   public abstract class NoteBook
   {
	   public abstract void SayHello();
   }
   
   public class Lenovo:NoteBook
   {
	   public override void SayHello()
	   {
		   Console.WriteLine("Lenovo...");
	   }
   }
   
   public class Acer:NoteBook
   {
	   public override void SayHello()
	   {
		   Console.WriteLine("Acer...");
	   }
   }
   
   public class Dell:NoteBook
   {
	   public override void SayHello()
	   {
		   Console.WriteLine("Dell...");
	   }
   }
} 

二.值传递和引用传递

(1)值类型:int double char decimal bool enum struct

(2)引用类型:string 数组 自定义类 集合 object 接口

Swap(ref n1.ref n2);
//交换两个变量的值
public static void Swap(ref int n1,ref int n2)
{
	int temp = n1;
	n1 = n2;
	n2 = temp;
}

三.序列化与反序列化(作用:传输数据)

序列化:将对象转换为二进制。

//指示一个类可以被序列化
[Serializable]
public class Person{}

四.部分类:同一个命名空间下不可以有两个重复的类。

public partial class Person
{
	private string _name;
}

public partial class Person
{
	public void Test()
	{
		_name = 10;	//可以使用_name
	}
}

五.密封类(其他类无法从密封类型派生)

public sealed class Person{}

六.显示实现接口(为了解决方法重名问题)

class Demo01
{
	static void Main(string[] args)
	{
		IFlyable ifl = new Bird();
		ifl.Fly();	//IFly...fly
		Bird b = new Bird();
		b.Fly();	//Bird...fly
		Console.Read();
	}	
}

public class Bird:IFlyable
{//编译器认为Fly()是实现接口的方法
	public void Fly()
	{
		Console.WriteLine("Bird...fly");
	}
	void IFlyable.Fly()	//显示实现接口(不能加修饰符,默认为private)
	{
		Console.WriteLine("IFly...fly");
	}
}

public interface IFlyable
{
	void Fly();
}









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值