C#扩展方法,使用this关键字
1、扩展方法能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。
2、扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。
3、C#扩展方法第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。
例子1(在泛型List<T>中扩展Random随机、Shuffle洗牌)
public static class List_Extension
{
public static T Random<T>(this List<T> list)
{
return list[Math.Random(0, list.Count - 1)];
}
public static void Shuffle<T>(this List<T> list)
{
int num = list.Count;
while (num > 1)
{
int index = Math.Random(0, --num);
T value = list[num];
list[num] = list[index];
list[index] = value;
}
}
}
例子2(在Array中扩展Random随机、Shuffle洗牌)
public static class Array_Extension
{
public static T Random<T>(this T[] array)
{
return array[Math.Random(0, array.Length - 1)];
}
public static void Shuffle<T>(this T[] array)
{
int num = array.Length;
while (num > 1)
{
int num2 = Math.Random(0, --num);
T val = array[num];
array[num] = array[num2];
array[num2] = val;
}
}
}
网友评论