自定义泛型链表
// 链表节点
public class Node<T>
{
public Node<T> Next { get; set; }
public T Data { get; set; }
public Node(T t)
{
Next = null;
Data = t;
}
}
//泛型链表类
public class GenericList<T>
{
private Node<T> head;
private Node<T> tail;
public GenericList()
{
tail = head = null;
}
public Node<T> Head
{
get => head;
}
public void Add(T t)
{
Node<T> n = new Node<T>(t);
if (tail == null)
{
head = tail = n;
}
else
{
tail.Next = n;
tail = n;
}
}
///////遍历方法////////
public void ForEach(Action<T> action)
{
Node<T> temp = head;
while (temp.Next != null)
{
action(temp.Data);
temp = temp.Next;
}
action(temp.Data);
}
}
实现一下遍历输出、求最大值、求和:
class Program
{
static void Main(string[] args)
{
// 整型List
GenericList<int> intlist = new GenericList<int>();
//赋值
for (int x = 0; x < 10; x++)
{
intlist.Add(x);
}
//打印元素
Console.WriteLine("打印元素:");
intlist.ForEach(i => Console.WriteLine(i));
//求最大值
Console.WriteLine("求最大值:");
int max = 0;
intlist.ForEach(delegate (int i) { if (max < i) max = i; });
Console.WriteLine(max);
//求和
Console.WriteLine("求和:");
int sum = 0;
intlist.ForEach(i => sum += i);
Console.WriteLine(sum);
}
}
some notes today
委托格式的声明:
delegate void Func(string n);
非匿名方法委托实例:
//静态方法
Func fun1 = new Func(Program.PrintAWord);
Func fun1 = Program.PrintAWord;//可以直接这么写,和用了new一样
//非静态方法
Func fun2 = new Func(anobject.PrintItsName);
Func fun2 = anobject.PrintItsName;//可以直接这么写,和用了new一样
匿名方法委托实例:
//匿名方法
Func printf1 = delegate (string s) {Console.WriteLine(s);};
//lambda表达式
Func printf = s => Console.WriteLine(s);
C#中List是泛型类型,相当于Java中的ArrayList。
C#中ArrayList是Object类型。
List<string> words = new List<string>(){
"Apple", "Banana", "Orange", "Mango"
};
List<T>.ForEach(Action<T> action)
可以实现foreach()
的功能
foreach (string s in words) {
printf(s);
}
相当于
words.ForEach(s => Console.WriteLine(s));