当前位置:网站首页>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 ,value
Represents 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()
{
//...
}
//...
}
边栏推荐
- SAP feature description
- Talking about fake demand from takeout order
- Analysis of postman core functions - parameterization and test report
- 5. Data access - entityframework integration
- 企业级数据安全,天翼云是这样理解的
- C final review
- Find in MySQL_ in_ Detailed explanation of set() function usage
- Oracle date format conversion to_ date,to_ char,to_ Timestamp mutual conversion
- 如何写出好代码 - 防御式编程
- EasyCVR电子地图中设备播放器loading样式的居中对齐优化
猜你喜欢
Thoroughly understand why network i/o is blocked?
How to automatically install pythn third-party libraries
How to write good code defensive programming
Applet modification style (placeholder, checkbox style)
1亿单身男女撑起一个IPO,估值130亿
Word查找红色文字 Word查找颜色字体 Word查找突出格式文本
[today in history] July 5: the mother of Google was born; Two Turing Award pioneers born on the same day
2022年阿里Android高级面试题分享,2022阿里手淘Android面试题目
【历史上的今天】7 月 5 日:Google 之母出生;同一天诞生的两位图灵奖先驱
Find in MySQL_ in_ Detailed explanation of set() function usage
随机推荐
Precautions for RTD temperature measurement of max31865 module
Powerful tool for collection processing
R language Visual scatter plot graph, add labels to some data points in the graph, and always display all labels, even if they have too much overlap. Ggrep package helps
输油管的布置数学建模matlab,输油管布置的数学模型
uniapp获取微信头像和昵称
7-2 保持链表有序
Quickly generate IPA package
Interprocess communication (IPC): shared memory
机器学习基础(三)——KNN/朴素贝叶斯/交叉验证/网格搜索
彻底理解为什么网络 I/O 会被阻塞?
紧固件行业供应商绩效考核繁琐?选对工具才能轻松逆袭!
XML basic knowledge concept
Isprs2020/ cloud detection: transferring deep learning models for cloud detection between landsat-8 and proba-v
进程间通信(IPC):共享内存
一文读懂简单查询代价估算
2022 the most complete Tencent background automation testing and continuous deployment practice in the whole network [10000 words]
C final review
[today in history] July 5: the mother of Google was born; Two Turing Award pioneers born on the same day
Blue sky drawing bed Apple quick instructions
常见时间复杂度