当前位置:网站首页>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()
{
//...
}
//...
}
边栏推荐
- 在线协作产品哪家强?微软 Loop 、Notion、FlowUs
- C final review
- 进程间通信(IPC):共享内存
- 块编辑器如何选择?印象笔记 Verse、Notion、FlowUs
- 企业数字化转型之路,从这里开始
- 2022 Alibaba Android advanced interview questions sharing, 2022 Alibaba hand Taobao Android interview questions
- Oracle Chinese sorting Oracle Chinese field sorting
- IDEA配置npm启动
- Linear table - abstract data type
- cf:B. Almost Ternary Matrix【对称 + 找规律 + 构造 + 我是构造垃圾】
猜你喜欢

Reptile 01 basic principles of reptile

Word finds red text word finds color font word finds highlighted formatted text

The era of Web3.0 is coming. See how Tianyi cloud storage resources revitalize the system to enable new infrastructure (Part 2)

MySQL数据库索引教程(超详细)

达梦数据库udf实现

Windows Oracle 开启远程连接 Windows Server Oracle 开启远程连接

Find in MySQL_ in_ Detailed explanation of set() function usage

You can have both fish and bear's paw! Sky wing cloud elastic bare metal is attractive!

Why can't Bi software do correlation analysis? Take you to analyze

MySQL优化六个点的总结
随机推荐
Solutions contents have differences only in line separators
AI表现越差,获得奖金越高?纽约大学博士拿出百万重金,悬赏让大模型表现差劲的任务
Precautions for RTD temperature measurement of max31865 module
Why can't Bi software do correlation analysis? Take you to analyze
Startup and shutdown of CDB instances
Mysql database indexing tutorial (super detailed)
Various pits of vs2017 QT
AI open2022 | overview of recommendation systems based on heterogeneous information networks: concepts, methods, applications and resources
max31865模块RTD测温注意事项
彻底理解为什么网络 I/O 会被阻塞?
C language makes it easy to add, delete, modify and check the linked list "suggested collection"
uniapp获取微信头像和昵称
Tianyi cloud understands enterprise level data security in this way
lombok @Builder注解
企业数字化转型之路,从这里开始
Deep copy and shallow copy [interview question 3]
The era of Web3.0 is coming. See how Tianyi cloud storage resources revitalize the system to enable new infrastructure (Part 2)
R language uses lubridate package to process date and time data
Oracle date format conversion to_ date,to_ char,to_ Timestamp mutual conversion
进程间通信(IPC):共享内存