using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Extend
{
/// <summary>
/// 扩展接口方法 扩展密封类方法
/// 静态类的静态方法
/// </summary>
public class Extend : MonoBehaviour, MathAdd
{
public int Add(int a, int b)
{
return a + b;
}
void Start()
{
this.Maltiply(1, 2);
Test a = new Test();
a.Divison(2, 1);
Test2 test2 = new Test2();
Math.Test2Extend(test2);
}
}
public class Test : MathAdd
{
public int Add(int a, int b)
{
return a + b;
}
}
//扩展接口 只要继承了MathAdd接口 都会有下面的方法
public static class Math
{
public static int Sub(this MathAdd mathAdd, int a, int b)
{
return a - b;
}
public static int Maltiply(this MathAdd mathAdd, int a, int b)
{
return a * b;
}
public static int Divison(this MathAdd mathAdd, int a, int b)
{
return a / b;
}
public static void Test2Extend(this Test2 test2)
{
test2.Show();
}
}
public interface MathAdd {
int Add(int a, int b);
}
public sealed class Test2
{
public void Show()
{
Debug.LogError("密封类的show方法");
}
}
//密封类无法继承
//public class Test2Extend : Test2
//{
//}
}
linq查询和扩展
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class Linq : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
List<Student> students = new List<Student>() {
new Student{
id = 1,
name = "aa",
age = 1
},
new Student{
id = 2,
name = "bb",
age = 14
},
new Student{
id = 3,
name = "cc",
age = 55
},
new Student{
id = 4,
name = "dd",
age = 20
},
new Student{
id = 5,
name = "ee",
age = 34
},
};
{
Debug.LogError("=============普通查询==================");
foreach (var item in students)
{
if (item.age <= 20)
Debug.LogError($"ID:{item.id},姓名:{item.name},年龄:{item.age}。");
}
}
{
Debug.LogError("=============扩展方法查询(linq)==================");
var list = students.Where(s => s.age <= 20);
foreach (var item in list)
{
Debug.LogError($"ID:{item.id},姓名:{item.name},年龄:{item.age}。");
}
}
{
Debug.LogError("=============关键词方式(linq)==================");
var list = from s in students
where s.age <= 20
select s;
foreach (var item in list)
{
Debug.LogError($"ID:{item.id},姓名:{item.name},年龄:{item.age}。");
}
}
{
Debug.LogError("=============自定义扩展Where(linq)==================");
var list = students.ExWhere(s => s.age <= 20);
foreach (var item in list)
{
Debug.LogError($"ID:{item.id},姓名:{item.name},年龄:{item.age}。");
}
}
}
}
class Student
{
public int id;
public string name;
public int age;
}
static class ExtendLinq
{
public static List<Student> ExWhere(this List<Student> list, Func<Student, bool> func)
{
var resous = new List<Student>();
foreach (var item in list)
{
//if (item.age <= 20)
//{
// resous.Add(item);
//}
if (func.Invoke(item))
{
resous.Add(item);
}
}
return resous;
}
public static List<T> ExWhere<T>(this List<T> list, Func<T, bool> func)
{
var resous = new List<T>();
foreach (var item in list)
{
if (func.Invoke(item))
{
resous.Add(item);
}
}
return resous;
}
}