当前位置:网站首页>Advanced application of C # language
Advanced application of C # language
2022-07-05 19:04:00 【Youth programming competition communication】
C# Advanced application of language

1、 attribute
example 1: Introduction of attribute concept ( problem )

public class Animal
{
public int Age;
public double Weight;
public bool Sex;
public Animal(int age, double weight, bool sex)
{
Age = age;
Weight = weight;
Sex = sex;
}
public void Eat()
{
Console.WriteLine("Animal Eat.");
}
public void Sleep()
{
Console.WriteLine("Animal Sleep.");
}
public override string ToString()
{
return string.Format("Animal Age:{0}, Weight:{1}, Sex:{2}", Age, Weight, Sex);
}
}
class Program
{
static void Main(string[] args)
{
Animal al = new Animal(1, 1.2, false);
Console.WriteLine("Animal Age:{0}, Weight:{1}, Sex:{2}", al.Age, al.Weight, al.Sex);
al.Age = -1;
al.Weight = -0.5;
Console.WriteLine(al);
}
}
example 2: Problem solving (Java Language solution to this problem )

public class Animal
{
private int _age;
private double _weight;
private readonly bool _sex;
public int GetAge()
{
return _age;
}
public void SetAge(int value)
{
_age = (value > 0) ? value : 0;
}
public double GetWeight()
{
return _weight;
}
public void SetWeight(double value)
{
_weight = (value > 0) ? value : 0;
}
public bool GetSex()
{
return _sex;
}
public Animal(int age, double weight, bool sex)
{
_age = (age > 0) ? age : 0;
_weight = (weight > 0) ? weight : 0;
_sex = sex;
}
public void Eat()
{
Console.WriteLine("Animal Eat.");
}
public void Sleep()
{
Console.WriteLine("Animal Sleep.");
}
public override string ToString()
{
return string.Format("Animal Age:{0}, Weight:{1}, Sex:{2}", _age, _weight, _sex);
}
}
class Program
{
static void Main(string[] args)
{
Animal al = new Animal(1, 1.2, false);
Console.WriteLine("Animal Age:{0},Weight:{1},Sex:{2}", al.GetAge(), al.GetWeight(), al.GetSex());
al.SetAge(-1);
al.SetWeight(-0.5);
Console.WriteLine(al);
}
}
example 3: The proposal of attributes

public class Animal
{
private int _age;
private double _weight;
private readonly bool _sex;
public int Age
{
get {
return _age; }
set {
_age = (value > 0) ? value : 0; }
}
public double Weight
{
get {
return _weight; }
set {
_weight = (value > 0) ? value : 0; }
}
public bool Sex
{
get {
return _sex; }
}
public Animal(int age, double weight, bool sex)
{
_age = (age > 0) ? age : 0;
_weight = (weight > 0) ? weight : 0;
_sex = sex;
}
public void Eat()
{
Console.WriteLine("Animal Eat.");
}
public void Sleep()
{
Console.WriteLine("Animal Sleep.");
}
public override string ToString()
{
return string.Format("Animal Age:{0}, Weight:{1}, Sex:{2}", Age, Weight, Sex);
}
}
class Program
{
static void Main(string[] args)
{
Animal al = new Animal(1, 1.2, false);
Console.WriteLine("Animal Age:{0}, Weight:{1}, Sex:{2}", al.Age, al.Weight, al.Sex);
al.Age = -1;
al.Weight = -0.5;
Console.WriteLine(al);
}
}
explain :C# In a statement data You can define set、get Method .
get: Define read operations .set: Define assignment operation ,valueRepresents the parameter value passed in .
example 4: Simplification of attributes

public class Animal
{
private int _age;
private double _weight;
public int Age
{
get {
return _age; }
set {
_age = (value > 0) ? value : 0; }
}
public double Weight
{
get {
return _weight; }
set {
_weight = (value > 0) ? value : 0; }
}
public bool Sex {
get; private set; }
public Animal(int age, double weight, bool sex)
{
_age = (age > 0) ? age : 0;
_weight = (weight > 0) ? weight : 0;
Sex = sex;
}
public void Eat()
{
Console.WriteLine("Animal Eat.");
}
public void Sleep()
{
Console.WriteLine("Animal Sleep.");
}
public override string ToString()
{
return string.Format("Animal Age:{0},Weight:{1},Sex:{2}", Age, Weight, Sex);
}
}
class Program
{
static void Main(string[] args)
{
Animal al = new Animal(1, 1.2, false);
Console.WriteLine("Animal Age:{0}, Weight:{1}, Sex:{2}", al.Age, al.Weight, al.Sex);
al.Age = -1;
al.Weight = -0.5;
Console.WriteLine(al);
}
}
explain : Attributes can be seen as an added layer of isolation for private data parts .
2、 Indexer
2.1 Definition
Is a special attribute in a collection class , It can make the elements in the collection class access like array elements .
2.2 Grammatical structure
public Element type this[int index]
{
get {
... }
set {
... }
}
public Element type this[string name]
{
get {
... }
set {
... }
}
example 5: Use indexer to realize the collection class StudentSet Medium element Student The interview of .

public class Student
{
private string _name;
public string Name
{
get {
return _name; }
set
{
_name = string.IsNullOrEmpty(value)
? "NULL"
: value;
}
}
public long ID {
get; set; }
public Student(long id, string name)
{
ID = id;
_name = name;
}
public override string ToString()
{
return string.Format("ID:{0},Name:{1}", ID, Name);
}
}
public class StudentSet
{
private readonly int _maxCount = 500;
private readonly Student[] _stus;
public int Count
{
get; private set;
}
public StudentSet()
{
Count = 0;
_stus = new Student[_maxCount];
}
public void Add(Student stu)
{
if (stu == null)
throw new ArgumentNullException();
if (Count == _maxCount)
throw new IndexOutOfRangeException();
_stus[Count] = stu;
Count++;
}
public Student this[int index]
{
get
{
if (index < 0 || index > Count - 1)
throw new IndexOutOfRangeException();
return _stus[index];
}
set
{
if (index < 0 || index > Count - 1)
throw new IndexOutOfRangeException();
if (value == null)
throw new ArgumentNullException();
_stus[index] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
StudentSet stuSet = new StudentSet();
stuSet.Add(new Student(10086, " Zhang San "));
stuSet.Add(new Student(95988, " Li Si "));
stuSet[1].Name = string.Empty;
Console.WriteLine(stuSet.Count);
Console.WriteLine(stuSet[0]);
Console.WriteLine(stuSet[1]);
Console.WriteLine(stuSet[2]);
// Unhandled exception : System.IndexOutOfRangeException: Index out of array bounds .
}
}
3、 Interface
3.1 Concept
- Interface is the blueprint of class design , That is, only the declaration is provided without implementation .
- Interfaces cannot directly instantiate objects ( Same as abstract class ).
- C# Allow a class to implement multiple interfaces ( Pay attention to the difference between inheritance ).
- An interface contains a series of methods that are not implemented , And hand over the implementation of these methods to the classes that inherit them .
3.2 Express

example 6: Use according to the class diagram Dog Realization IAnimal Interface

public interface IAnimal
{
int Age {
get; set; }
double Weight {
get; set; }
void Eat();
void Sleep();
}
public class Dog : IAnimal
{
private int _age;
private double _weight;
public int Age
{
get {
return _age; }
set {
_age = (value >= 0) ? value : 0; }
}
public double Weight
{
get {
return _weight; }
set {
_weight = (value >= 0) ? value : 0; }
}
public void Eat()
{
Console.WriteLine("Dog Eat");
}
public void Sleep()
{
Console.WriteLine("Dog Sleep");
}
}
class Program
{
static void Main(string[] args)
{
IAnimal al = new Dog();
al.Age = 1;
al.Weight = 2.5;
Console.WriteLine("Dog:Age={0}, Weight={1}", al.Age, al.Weight);
al.Eat();
al.Sleep();
}
}
example 7: Use the interface to realize “ Feeding system ”
A breeder (Raiser) At present, three kinds of animals need to be raised : Dog (Dog)、 bird (Bird) And fish (Fish), The three animals only need to sleep (Sleep) And eating (Eat) that will do . Please design the feeding system , It is required to meet the requirements of software design “ Opening and closing principle ”.
Scheme 1 :( It has been given in the abstract class section )

Option two :

public interface IAnimal
{
int Age {
get; set; }
double Weight {
get; set; }
void Eat();
void Sleep();
}
public class Bird : IAnimal
{
private int _age;
private double _weight;
public int Age
{
get {
return _age; }
set {
_age = (value >= 0) ? value : 0; }
}
public double Weight
{
get {
return _weight; }
set {
_weight = (value >= 0) ? value : 0; }
}
public void Eat()
{
Console.WriteLine("Bird Eat.");
}
public void Sleep()
{
Console.WriteLine("Bird Sleep.");
}
public void Fly()
{
Console.WriteLine("Bird Fly.");
}
}
public class Dog : IAnimal
{
private int _age;
private double _weight;
public int Age
{
get {
return _age; }
set {
_age = (value >= 0) ? value : 0; }
}
public double Weight
{
get {
return _weight; }
set {
_weight = (value >= 0) ? value : 0; }
}
public void Eat()
{
Console.WriteLine("Dog Eat.");
}
public void Sleep()
{
Console.WriteLine("Dog Sleep.");
}
public void Run()
{
Console.WriteLine("Dog Run.");
}
}
public class Fish : IAnimal
{
private int _age;
private double _weight;
public int Age
{
get {
return _age; }
set {
_age = (value >= 0) ? value : 0; }
}
public double Weight
{
get {
return _weight; }
set {
_weight = (value >= 0) ? value : 0; }
}
public void Eat()
{
Console.WriteLine("Fish Eat.");
}
public void Sleep()
{
Console.WriteLine("Fish Sleep.");
}
public void Swim()
{
Console.WriteLine("Fish Swim.");
}
}
public class Raiser
{
public void Raise(IAnimal al)
{
al.Eat();
al.Sleep();
}
}
class Program
{
static void Main(string[] args)
{
Raiser rsr = new Raiser();
rsr.Raise(new Dog());
rsr.Raise(new Bird());
rsr.Raise(new Fish());
}
}
3.3 Interface (interface) And abstract classes (abstract class)
(1) The same thing :
- Neither interfaces nor abstract classes can directly instantiate objects .
(2) Difference :
- Data and operations in abstract classes must have restriction modifiers , The data and operations in the interface cannot have restriction modifiers .
- Abstract classes can have methods with implementations ( Not abstract Method ), Interfaces can only have method declarations .
- Abstract classes pass in subclasses override Keyword override abstract method , The interface is directly implemented by subclasses .
example 8: A class can implement multiple interfaces , However, you should pay attention to the handling of duplicate methods in multiple interfaces .
Mode one :

public interface IHighWayWorker
{
void HighWayOperation();
void Build();
}
public interface IRailWayWorker
{
void RailWayOperation();
void Build();
}
public class Worker : IRailWayWorker, IHighWayWorker
{
public void HighWayOperation()
{
Console.WriteLine("HighWayOperation.");
}
public void RailWayOperation()
{
Console.WriteLine("RailWayOperation");
}
public void Build()
{
Console.WriteLine("HighWay,RailWay,Build.");
}
}
class Program
{
static void Main(string[] args)
{
Worker wr = new Worker();
wr.Build(); // HighWay,RailWay,Build.
IHighWayWorker hwr = new Worker();
hwr.Build(); // HighWay,RailWay,Build.
hwr.HighWayOperation(); // HighWayOperation.
IRailWayWorker rwr = new Worker();
rwr.Build(); // HighWay,RailWay,Build.
rwr.RailWayOperation();// RailWayOperation
}
}
Mode two :

public interface IHighWayWorker
{
void HighWayOperation();
void Build();
}
public interface IRailWayWorker
{
void RailWayOperation();
void Build();
}
public class Worker : IHighWayWorker, IRailWayWorker
{
public void HighWayOperation()
{
Console.WriteLine("HighWayOperation.");
}
public void RailWayOperation()
{
Console.WriteLine("RailWayOperation");
}
void IHighWayWorker.Build()
{
Console.WriteLine("HighWay Build.");
}
void IRailWayWorker.Build()
{
Console.WriteLine("RailWay Build.");
}
// Be careful :void IHighWayWorker.Build() and void IRailWayWorker.Build()
// No restriction modifier can be added in front .
}
class Program
{
static void Main(string[] args)
{
Worker wr = new Worker();
//wr.Build(); The statement is incorrect
IHighWayWorker hwr = new Worker();
hwr.Build();//HighWay Build.
hwr.HighWayOperation();//HighWayOperation.
IRailWayWorker rwr = new Worker();
rwr.Build();//RailWay Build.
rwr.RailWayOperation();//RailWayOperation
}
}
4、 Generic
example 9: Storage int Collection and operation of data types .
public class IntSet
{
private readonly int _maxSize;
private readonly int[] _set;
public IntSet()
{
_maxSize = 100;
_set = new int[_maxSize];
//...
}
public void Insert(int k, int x)
{
//....
_set[k] = x;
}
public int Locate(int k)
{
//...
return _set[k];
}
}
class Program
{
static void Main(string[] args)
{
IntSet iSet = new IntSet();
iSet.Insert(0, 123);
int i = iSet.Locate(0);
Console.WriteLine(i); // 123
}
}
example 10: Storage string Collection and operation of data types .
public class StringSet
{
private readonly int _maxSize;
private readonly string[] _set;
public StringSet()
{
_maxSize = 100;
_set = new string[_maxSize];
//...
}
public void Insert(int k, string x)
{
//....
_set[k] = x;
}
public string Locate(int k)
{
//...
return _set[k];
}
}
class Program
{
static void Main(string[] args)
{
StringSet strSet = new StringSet();
strSet.Insert(0, "abc");
string j = strSet.Locate(0);
Console.WriteLine(j); // abc
}
}
example 11: utilize object Class stores collections and operations of general data types .
public class GSet
{
private readonly int maxSize;
private readonly object[] _set;
public GSet()
{
maxSize = 100;
_set = new object[maxSize];
//...
}
public void Insert(int k, object x)
{
//....
_set[k] = x;
}
public object Locate(int k)
{
//...
return _set[k];
}
}
class Program
{
static void Main(string[] args)
{
GSet gSet1 = new GSet();
gSet1.Insert(0, 123);
int k1 = (int)gSet1.Locate(0);
Console.WriteLine(k1); // 123
GSet gSet2 = new GSet();
gSet2.Insert(0, "abc");
string k2 = (string)gSet2.Locate(0);
Console.WriteLine(k2); // abc
GSet gSet3 = new GSet();
gSet3.Insert(0, 123);
gSet3.Insert(1, "abc");// At compile time, you can use , Exception at runtime .
int k3 = (int)gSet3.Locate(1); // There is a type safety problem in this way .
Console.WriteLine(k3);
// Unhandled exception : System.InvalidCastException: Invalid conversion specified .
}
}
Generic definition : I.e. parameterized type .
Replace the parameter type with a specific type at compile time , Type safe classes can be defined without affecting work efficiency .
example 12: Using generics T Store collections and operations of common data types .
public class GSet<T>
{
private readonly int _maxSize;
private readonly T[] _set;
public GSet()
{
_maxSize = 100;
_set = new T[_maxSize];
//...
}
public void Insert(int k, T x)
{
//....
_set[k] = x;
}
public T Locate(int k)
{
//...
return _set[k];
}
}
class Program
{
static void Main(string[] args)
{
GSet<int> gSet1 = new GSet<int>();
gSet1.Insert(0, 123);
int k1 = gSet1.Locate(0);
Console.WriteLine(k1); // 123
GSet<string> gSet2 = new GSet<string>();
gSet2.Insert(0, "abc");
string k2 = gSet2.Locate(0);
Console.WriteLine(k2); // abc
}
}
We put T This is called a type parameter , Of course, we can also deal with T Constraint .
example 13: Is a type parameter T Add constraints , such as T Can only be value type .
public class GSet<T> where T : struct
{
private readonly int _maxSize;
private readonly T[] _set;
public GSet()
{
_maxSize = 100;
_set = new T[_maxSize];
//...
}
public void Insert(int k, T x)
{
//....
_set[k] = x;
}
public T Locate(int k)
{
//...
return _set[k];
}
}
class Program
{
static void Main(string[] args)
{
GSet<int> gSet1 = new GSet<int>();
gSet1.Insert(0, 123);
int k1 = gSet1.Locate(0);
Console.WriteLine(k1); // 123
// GSet<string> gSet2 = new GSet<string>(); // Compile error
// error CS0453 type “string” Must be cannot be null The type of value ,
// Can be used as a generic type or method “GSet < T >” Parameters in “T”
}
}
For generic constraints, see the following diagram :
5、 The relationship between classes

public class Oxygen
{
//...
}
public class Water
{
//...
}
public abstract class Animal
{
public int Age;
public double Weight;
public abstract void Eat();
public abstract void Sleep();
public abstract void Breed();
public abstract void Metabolism(Oxygen o2, Water water);
}

public class Bird : Animal
{
public string Feather;
public void Fly()
{
//...
}
public void Egg()
{
//...
}
public override void Eat()
{
//...
}
public override void Sleep()
{
//...
}
public override void Breed()
{
//...
}
public override void Metabolism(Oxygen o2, Water water)
{
//...
}
}
public class Penguin : Bird
{
//...
}
public class Goose : Bird
{
//...
}
public class Duck : Bird
{
//...
}

public class Climate
{
//...
}
public class Penguin : Bird
{
private Climate _climate;
//...
}

public interface ILanguage
{
void Speak();
}
public class DonaldDuck : Duck, ILanguage
{
public void Speak()
{
//...
}
//...
}
边栏推荐
- 2022最新大厂Android面试真题解析,Android开发必会技术
- 视频自监督学习综述
- 解决 contents have differences only in line separators
- 使用文件和目录属性和属性
- XML基础知识概念
- Windows Oracle 开启远程连接 Windows Server Oracle 开启远程连接
- Ant group open source trusted privacy computing framework "argot": open and universal
- Use file and directory properties and properties
- c语言简便实现链表增删改查「建议收藏」
- android中常见的面试题,2022金九银十Android大厂面试题来袭
猜你喜欢

Chinese postman? Really powerful!

图扑软件数字孪生 | 基于 BIM 技术的可视化管理系统

深入底层C源码讲透Redis核心设计原理

5. 数据访问 - EntityFramework集成

从外卖点单浅谈伪需求

Various pits of vs2017 QT

2022全网最全的腾讯后台自动化测试与持续部署实践【万字长文】

AI open2022 | overview of recommendation systems based on heterogeneous information networks: concepts, methods, applications and resources

尚硅谷尚优选项目教程发布

【历史上的今天】7 月 5 日:Google 之母出生;同一天诞生的两位图灵奖先驱
随机推荐
中文版Postman?功能真心强大!
尚硅谷尚优选项目教程发布
What are the cache interfaces of nailing open platform applet API?
企业数字化转型之路,从这里开始
Postman核心功能解析 —— 参数化和测试报告
进程间通信(IPC):共享内存
Video fusion cloud platform easycvr adds multi-level grouping, which can flexibly manage access devices
How to write good code defensive programming
2022年5月腾讯云开发者社区视频月度榜单公布
Overview of video self supervised learning
使用文件和目录属性和属性
Powerful tool for collection processing
c语言简便实现链表增删改查「建议收藏」
Is the performance evaluation of suppliers in the fastener industry cumbersome? Choose the right tool to easily counter attack!
视频自监督学习综述
技术分享 | 接口测试价值与体系
决策树与随机森林
Linear table - abstract data type
Is it safe to make fund fixed investment on access letter?
一朵云开启智慧交通新未来