C# 扩展方法
C# 扩展方法
扩展方法能给类添加方法,但是不改变原来类的任何内容。原来的类也不需要任何编译的过程
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 扩展方法
{
class Program
{
static void Main(string[] args)
{
var number = "100好";
number.StringToIntSquare();
Console.ReadKey();
}
}
//扩展方法所在的类必须是静态类,且该扩展方法只能是静态方法
internal static class ClassExtension
{
//this代表调用该方法的对象实例,该对象为String类型
public static void StringToIntSquare(this string txt)
{
int temp;
int.TryParse(txt,out temp);
if (temp==0)
{
Console.WriteLine("字符串不合法!");
return;
}
Console.WriteLine(Math.Sqrt(temp).ToString());
}
}
}
先决条件
- 扩展方法必须在一个非嵌套、非泛型的静态类中定义
- 扩展方法必须是一个静态方法
- 扩展方法至少要有一个参数
- 第一个参数必须附加this关键字作为前缀
- 第一个参数不能有其他修饰符(比如ref或者out)
- 第一个参数不能是指针类型
注意事项
- 跟前面提到的几个特性一样,扩展方法只会增加编译器的工作,不会影响性能(用继承的方式为一个类型增加特性反而会影响性能)
- 如果原来的类中有一个方法,跟你的扩展方法一样(至少用起来是一样),那么你的扩展方法奖不会被调用,编译器也不会提示你
- 扩展方法太强大了,会影响架构、模式、可读性等等等等….