最近又重新回过头来学习C#,才发现之前学习的知识有多么的浅显,有些东西还是挺难懂的,但是比较有意思,例如协变,逆变,不变就挺有意思,但是也挺绕,下面是学习过程中写的一些代码,有点乱,就当日记记叙一下。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Genericity泛型 { //泛型委托 public delegate R MyDelegate<T, R>(T t); class Program { static void Main(string[] args) { MyStack<int> stack = new MyStack<int>(5); var stack1 = new MyStack<string>(8); while(!stack.IsFull) { stack.Push(2); } while(!stack.IsEmpty) { stack.Pop(); } MyDelegate<string, string> s; s = stack.PrintString; //Lambda表达式 s += (string a) => { return a; }; Console.WriteLine(s("safa")); Console.WriteLine("这个栈的长度为:{0}",stack.GetLength<int>()); Console.ReadKey(); } } //顺序栈,泛型 public class MyStack<T> { T[] StackArray; public int Length; int StackPointer; public string PrintString(string a) { return a; } public bool IsEmpty { get { return StackPointer == 0 ? true : false; } } public bool IsFull { get { return StackPointer >= Length ? true : false; } } public MyStack(int _length) { Length = _length; StackArray = new T[Length]; StackPointer = 0; } public void Push(T _value) { if (IsFull) { Console.WriteLine("栈已经满"); } StackArray[StackPointer++] = _value; } public void Pop() { if (IsEmpty) { Console.WriteLine("栈已空"); } Console.WriteLine(StackArray[--StackPointer]); } public void StackPrint() { foreach (var i in StackArray) { Console.WriteLine(i); } } } //拓展方法 public static class ExtendStack { public static int GetLength<T>(this MyStack<T> ms) { return ms.Length; } } }
时间: 2024-10-24 02:14:47