C# Basic Introduction Day 13 (Polymorphic Interface)

Twelfth day review

namespace 复习
{
class Program
{
    static void Main(string[] args)
    {
        /*
         Lisi<T>
         Dictionary<K,T>
         拆装箱
         装箱:值类型转为引用类型
         拆箱:引用类型转为值类型
         应该尽量避免在代码中发生

         文件流
         FileStream  StreamReader和StreamWrite
         多态:虚方法、抽象类、接口
         虚方法
         抽象类
         */

        //List<int> list = new List<int>();

        //Dictionary<int, string> dic = new Dictionary<int, string>();
        //dic.Add(1, "张三");
        //dic[2] = "李四";
        //foreach (KeyValuePair<int ,string> kv in dic)
        //{
        //    Console.WriteLine("{0}----{1}", kv.Key, kv.Value);
        //}
        //Console.ReadKey();

        //File   FileStream  StreamReader  StreamWrite
        //using (FileStream fsRead = new FileStream("1.txt", FileMode.OpenOrCreate, FileAccess.Read))
        //{
        //    byte[] buffer = new byte[1024 * 1024 * 5];
        //    int r = fsRead.Read(buffer, 0, buffer.Length);
        //    string s = Encoding.UTF8.GetString(buffer, 0, r);
        //    Console.WriteLine(s);
        //}
        //Console.ReadKey();

        //using (FileStream fsWrite = new FileStream(@"C:\Users\Administrator\Desktop\new.txt", FileMode.OpenOrCreate, FileAccess.Write))
        //{
        //    string s = "今天的内容有点多啊";
        //    byte[] buffer = Encoding.UTF8.GetBytes(s);
        //    fsWrite.Write(buffer, 0, buffer.Length);
        //}
        //Console.WriteLine("OK");
        //Console.ReadKey();

        //虚方法和抽象类
        //老师可以起立,学生也可以起立,校长也可以起立
        //Person p = new Student();
        //p.StanUp();
        //Console.ReadKey();
    }
}
public abstract class Person
{
    public abstract void StanUp();
}

public class Student : Person
{
    public override void StanUp()
    {
        Console.WriteLine("学生起立,说老师好");
    }
}

public class Teachar : Person
{
    public override void StanUp()
    {
        Console.WriteLine("老师起立说校长好");
    }
}

public class HeadMaster : Person
{
    public override void StanUp()
    {
        Console.WriteLine("请坐");
    }
}

}

New content for the thirteenth day
1. Access modifiers in C#
public: public, public
private: private, only accessible inside the current class
protected: protected, only inside the current class and the class Access
internal in the subclass of : can only be accessed in the current assembly, and has the same permissions as public in the same project.
protected internal: add the permissions of protected and internal

1. The only access modifiers that can modify the class are public and internal
. 2. The accessibility of the
sub-class cannot be higher than that of the parent class, otherwise the members of the parent class will be exposed

2. Design pattern (a way to design this project.)
Simple factory design pattern

namespace _03简单工厂设计模式
{
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("请输入你需要的笔记本品牌");
        string note = Console.ReadLine();
        NoteBook nb = GetNoteBook(note);
        nb.SayHello();
        Console.ReadKey();
    }

    /// <summary>
    /// 简单工厂的核心,根据用户输入的对象来赋值给父类
    /// </summary>
    /// <param name="note"></param>
    /// <returns></returns>
    public static NoteBook GetNoteBook(string note)
    {
        NoteBook nb = null;
        switch (note)
        {
            case "Lenove" : nb = new Lenovo();
                break;
            case "Acre" : nb = new Acre();
                break;
            case "Dell" : nb = new Dell();
                break;
            case "Hp" : nb = new Hp();
                break;
        }
        return nb;
    }
}

public abstract class NoteBook
{
    public abstract void SayHello();
}

public class Lenovo : NoteBook
{
    public override void SayHello()
    {
        Console.WriteLine("我是联想笔记本,你连想都别想");
    }
}

public class Acre : NoteBook
{
    public override void SayHello()
    {
        Console.WriteLine("我是宏碁笔记本");
    }
}

public class Dell : NoteBook
{
    public override void SayHello()
    {
        Console.WriteLine("我是戴尔笔记本");
    }
}

public class Hp : NoteBook
{
    public override void SayHello()
    {
        Console.WriteLine("我是惠普笔记本");
    }
}
}

Third, the transfer of value types and reference types When the
value type is copied, it is the value itself. When the
reference type is copied, the reference to this object is passed.

4. Serialization and deserialization Serialization
: Convert the object to binary
Deserialization: Convert binary to object
Function: Transfer data
serialization:
1. Mark this class as serializable, and add a key to the class Word: [Serializable]

grammar

namespace _04序列化和反序列化
{
class Program
{
    static void Main(string[] args)
    {
        ////序列化
        //Person p = new Person();
        //p.Name = "张三";
        //p.Age = 18;
        //p.Gender = '男';
        //using (FileStream fsWrite = new FileStream(@"C:\Users\Administrator\Desktop\111.txt", FileMode.OpenOrCreate, FileAccess.Write))
        //{
        //    //开始序列化对象
        //    BinaryFormatter bf = new BinaryFormatter();
        //    bf.Serialize(fsWrite, p);
        //}
        //Console.WriteLine("写入成功");
        //Console.ReadKey();

        //接收对方发送过来的二进制 反序列化成对象
        Person p;
        using (FileStream fsRead = new FileStream(@"C:\Users\Administrator\Desktop\111.txt", FileMode.OpenOrCreate, FileAccess.Read))
        {
            BinaryFormatter bf = new BinaryFormatter();
           p = (Person)bf.Deserialize(fsRead);
        }
        Console.WriteLine(p.Name);
        Console.WriteLine(p.Age);
        Console.WriteLine(p.Gender);
        Console.ReadKey();
    }
}

[Serializable]
public class Person
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
    private int _age;
    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }
    private char _gender;
    public char Gender
    {
        get { return _gender; }
        set { _gender = value; }
    }
}
}

Five, some classes
are written with the same name in the same namespace, keyword: partial is
mostly used for multi-person development, you need to write a class
syntax

public partial class Person

Six, sealed classes
cannot be inherited, but sealed classes can inherit other class
syntax
public sealed class Person

Seven, rewrite the ToString method,
all things can be ToString, it should be ToString is a method of Object, all objects are subclass
syntax of Object

namespace _05重写ToString方法
{
class Program
{
    static void Main(string[] args)
    {
        Person p = new Person();
        Console.WriteLine(p.ToString());
        Console.ReadKey();
    }
}

public class Person
{
    public override string ToString()
    {
        return "Hello word";
    }
}
}

8. Interface (interface is a specification, capability)
syntax
[public] interface I...able
{
//The members in the interface are not allowed to add access modifiers, the default is public
//In the interface, functions with method bodies are not allowed , Cannot include fields
//In the interface, you can write automatic attributes (not written, but will be automatically generated when compiling)
public int Age
{
get;
set;
}
Members...
}

The members of the interface are: methods, automatic attributes, and indexers. However: automatic attributes are essentially two functions, and indexers are also functions. So: the members of the interface have: methods

The characteristics of the
interface : an interface is a specification, as long as a class inherits an interface, the class must implement all the members of the interface

public class Person : IFyable
{
    //实现这个接口中所有的成员
    public void Fly()
    {
        Console.WriteLine("飞");
    }
}

public interface IFyable
{
    void Fly();
}

For polymorphism, the interface cannot be instantiated. In other words, the interface cannot be new (objects cannot be created)

static void Main(string[] args)
    {
        //接口是不能被实例化的,因为接口中的成员没有方法体
        // IFyable fly = new IFyable();
        //如果要想实现多态,则需要指向一个对象
        IFyable fly = new Person();
        fly.Fly();
        Console.ReadKey();
    }

"Access modifiers" cannot be added to the members of the interface. The member access modifiers in the interface are public by default and cannot be modified. The members in the interface cannot have any implementation ("just talk without practice", just define a group of unimplemented members. Similar to abstract functions in abstract classes)

There can only be methods, automatic properties, indexers, and events in the interface, but not "fields" and constructors

Interface and interface can inherit, and can inherit multiple

public interface M1
{
    void Test1();
}
public interface M2
{
    void Test2();
}
public interface M3
{
    void Test3();
}
public interface M4:M1,M2,M3
{

}
public class Cat : M4
{
    public void Test1()
    {
        throw new NotImplementedException();
    }

    public void Test2()
    {
        throw new NotImplementedException();
    }

    public void Test3()
    {
        throw new NotImplementedException();
    }
}

An interface cannot inherit a class, and a class can inherit an interface (an interface can only inherit from an interface, and a class can inherit an interface or a class) to
implement subclasses of the interface, all members of the interface must be implemented.
One class can simultaneously Inherit a class and implement multiple interfaces, if a subclass also inherits the parent class A. And implement the interface interface IA, then the syntax A must be written in front of the IA
syntax:
public class B: A, IA
{
class member
}

Since this set of videos on the entire network has problems with the interface, I will leave it to the review

namespace _06接口
{
class Program
{
    static void Main(string[] args)
    {
        //接口是不能被实例化的,因为接口中的成员没有方法体
        // IFyable fly = new IFyable();
        //如果要想实现多态,则需要指向一个对象
        IFyable fly = new Person();
        fly.Fly();
        Console.ReadKey();
    }
}

public class Person : IFyable
{
    //实现这个接口中所有的成员
    public void Fly()
    {
        Console.WriteLine("飞");
    }
}

public interface IFyable
{
    void Fly();
}

public interface M1
{
    void Test1();
}
public interface M2
{
    void Test2();
}
public interface M3
{
    void Test3();
}
public interface M4:M1,M2,M3
{

}
public class Cat : M4
{
    public void Test1()
    {
        throw new NotImplementedException();
    }

    public void Test2()
    {
        throw new NotImplementedException();
    }

    public void Test3()
    {
        throw new NotImplementedException();
    }
}
}

Nine, display the
grammar and usage of the implementation interface (in order to solve the problem of the same name of the method)

namespace _07显示实现接口
{
class Program
{
    static void Main(string[] args)
    {
        IFlyable fly = new bird();
        fly.Fly();
        bird bi = new bird();
        bi.Fly();
        Console.ReadKey();
    }
}

public class bird:IFlyable
{
    public void Fly()
    {
        Console.WriteLine("鸟会飞");
    }
    /// <summary>
    /// 显示实现接口
    /// </summary>
    void IFlyable.Fly()
    {
        Console.WriteLine("我是接口的飞");
    }
}

public interface IFlyable
{
    void Fly();
}
}

Summary:
1. When to use virtual methods to achieve polymorphism.
In the provided class, a parent class can be abstracted. The parent class must write the methods shared by the subclasses, know how to write this method, and also need to create the parent class Object, then use virtual methods

2. When to use abstract classes to achieve polymorphism.
In the provided classes, a parent class can be abstracted. The parent class must write the methods shared by the subclasses, and do not know how to write this method, then use the abstract class

3. When to use interfaces to implement polymorphism
. Among several classes, the parent class cannot be found, but they all have a common behavior, so use the interface right away

Interface exercise

namespace _08接口练习
{
class Program
{
    static void Main(string[] args)
    {
        //真的鸭子会游泳,木头鸭子不会游泳,橡皮鸭子会游泳
        ISwimming swim = new RealDuck();
        swim.Swim();
        Console.ReadKey();
    }
}

public class RealDuck : ISwimming
{
    public void Swim()
    {
        Console.WriteLine("真的鸭子会游泳");
    }
}
public class MuDuck
{

}
public class XPDuck : ISwimming
{
    public void Swim()
    {
        Console.WriteLine("橡皮鸭子漂着游泳");
    }
}

public interface ISwimming
{
    void Swim();
}
}

Comprehensive actual combat: supermarket cashier system

Analyze system requirements
. Products provided by supermarkets: laptops, mobile phones, soy sauce, and bananas.
Products in the supermarket should have: price, quantity, number.
This can abstract a parent category (ProductFather), including price (Price) and quantity (Count) , Number (ID)

If the things are not enough to sell, you need to go to the warehouse to get
the functions needed by the warehouse: store goods, pick up, and purchase

When supermarkets sell things, they need a cash register function

Abstract the parent category of a commodity

class ProductFather
{
    public decimal Price
    {
        get;
        set;
    }

    public double Count
    {
        get;
        set;
    }

    public string ID
    {
        get;
        set;
    }

    public ProductFather(string id, decimal price, double count)
    {
        this.ID = id;
        this.Price = price;
        this.Count = count;
    }
}

Create product classes separately and inherit from the parent class

class ShouJi:ProductFather
{
    public ShouJi(string id, decimal price, double count) : base(id, price, count)
    {

    }
}

Create a warehouse class

class CangKu
{
//1. Store goods
//1.1 list is equivalent to a warehouse, and List<ProductFather> adds a collection of data, which is equivalent to putting shelves in a warehouse, so as to classify
List<List<ProductFather>> list = new List<List< ProductFather>>();

    /// <summary>
    /// 想用户展示货物
    /// </summary>
    public void ShowPros()
    {
        foreach (var item in list)
        {
            Console.WriteLine("仓库有:" + item[0].Name + "," + "\t" + "有" + item.Count + "个," + "\t" + "每个" + item[0].Price + "元。");
        }
    }

    /// <summary>
    /// 创建仓库对象时,向仓库中添加货架
    /// </summary>
    //list[0] 存电脑  list[1]存手机 list[2]存酱油 list[3]存香蕉,这时候如果多,就能通过循环来完成
    public CangKu()
    {
        list.Add(new List<ProductFather>());
        list.Add(new List<ProductFather>());
        list.Add(new List<ProductFather>());
        list.Add(new List<ProductFather>());
    }

    /// <summary>
    /// 进货
    /// </summary>
    /// <param name="strType">货物的类型</param>
    /// <param name="count">货物的数量</param>
    public void GetPros(string strType,int count)
    {
        for (int i = 0; i < count; i++)
        {
            switch (strType)
            {
                case "NoteBook": list[0].Add(new NoteBook(Guid.NewGuid().ToString(), 5000, "笔记本电脑"));
                    break;
                case "ShouJi":list[1].Add(new ShouJi(Guid.NewGuid().ToString(), 3000, "手机"));
                    break;
                case "JiangYou":list[2].Add(new JiangYou(Guid.NewGuid().ToString(), 10, "酱油"));
                    break;
                case "Banana":list[3].Add(new Banana(Guid.NewGuid().ToString(), 20, "香蕉"));
                    break;
            }
        }
    }

    /// <summary>
    /// 取货
    /// </summary>
    /// <param name="strType">货物的类型</param>
    /// <param name="count">货物的数量</param>
    //货物取出后,需要放哪?而且有可能会拿很多个所以返回ProductFather[]
    public ProductFather[] QuPros(string strType, int count)
    {
        ProductFather[] pros = new ProductFather[count];
        for (int i = 0; i < count; i++)
        {
            switch (strType)
            {
                case "NoteBook":
                    if (list[0].Count == 0)
                    {
                        Console.WriteLine("没有电脑了!");
                    }
                    else
                    {
                        pros[i] = list[0][0];
                        list[0].RemoveAt(0);
                    }
                    break;
                case "ShouJi":
                    if (list[1].Count == 0)
                    {
                        Console.WriteLine("没有手机了!");
                    }
                    else
                    {
                        pros[i] = list[1][0];
                        list[1].RemoveAt(0);
                    }
                    break;
                case "JiangYou":
                    if (list[2].Count == 0)
                    {
                        Console.WriteLine("没有酱油了!");
                    }
                    else
                    {
                        pros[i] = list[2][0];
                        list[2].RemoveAt(0);
                    }
                    break;
                case "Banana":
                    if (list[3].Count == 0)
                    {
                        Console.WriteLine("没有酱油了!");
                    }
                    else
                    {
                        pros[i] = list[3][0];
                        list[3].RemoveAt(0);
                    }
                    break;
            }
        }
        return pros;
    }
}

Guess you like

Origin blog.51cto.com/13544652/2598031