C#入门--多态(二)

来源:互联网 发布:ubuntu 双系统 主分区 编辑:程序博客网 时间:2024/06/04 19:11

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...flyBird b = new Bird();b.Fly();//Bird...flyConsole.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();}









原创粉丝点击