简易总结
定义:非泛型在静态类中,定义静态方法->>扩展方法
使用场合:
1.调用密封类中的对象,属性,或者方法(扩展密封类)。
2.扩展接口
3.在Linq链式编程中
实例一、
先定义一个类,假如这个类是别人那里拿过来的,不是自己写的 sealed 密封类 写一个静态类进行调用
public sealed class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Phone { get; set; }
/// <summary>
/// 返回电话
/// </summary>
/// <returns></returns>
public string GetPhone()
{
return Phone;
}
}
再定义一个静态类,写一个静态方法
/// <summary>
/// 调用密封类 定义一个静态类,再写一个静态方法
/// </summary>
public static class PersonExtend
{
public static void ShowPhone(this Person person)
{
Console.WriteLine(person.GetPhone());
}
}
最后调用
static void Main(string[] args)
{
Person person = new Person()
{
Age = 20,
Name = "ceshi",
Phone = "12345678900"
};
PersonExtend.ShowPhone(person);
Console.ReadKey();
}
运行结果:
实例二、扩展接口 定义一个接口
public interface ICalculate
{
int Add(int a, int b);
}
定义一个扩展接口
/// <summary>
/// 扩展类和扩展方法,要写成静态的
/// </summary>
public static class InterfaceExtend
{
public static int Sub(this ICalculate calculate, int a, int b)
{
return a - b;
}
public static int Maltiply(this ICalculate calculate, int a, int b)
{
return a * b;
}
public static int Division(this ICalculate calculate, int a, int b)
{
return a / b;
}
}
定义一个类,进行实现此扩展接口
public class A : ICalculate
{
public int Add(int a, int b)
{
return a + b;
}
}
进行实现
static void Main(string[] args)
{
A a = new A();
Console.WriteLine(a.Maltiply(2, 3));
C c = new C();
Console.WriteLine(c.Division(2, 3));
Console.ReadKey();
}
运行结果:
实例三、
Linq
最常见的扩展方法是 LINQ 标准查询运算符,它将查询功能添加到现有的
System.Collections.IEnumerable
和
System.Collections.Generic.IEnumerable<T>
类型。 若要使用标准查询运算符,请先使用
using System.Linq
指令将它们置于范围中。 然后,任何实现了
IEnumerable<T>
的类型看起来都具有
GroupBy
、
OrderBy
、
Average
等实例方法。 在
IEnumerable<T>
类型的实例(如
List<T>
或
Array
)后键入“dot”时,可以在 IntelliSense 语句完成中看到这些附加方法。
OrderBy的源代码
[__DynamicallyInvokable]
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
return new OrderedEnumerable<TSource, TKey>(source, keySelector, null, descending: false);
}
static void Main(string[] args)
{
int[] ints = { 10, 45, 15, 39, 21, 26 };
var result = ints.OrderBy(g => g);
foreach (var i in result)
{
System.Console.Write(i + " ");
}
Console.ReadKey();
}