一、扩展方法必须符合以下要求
1.方法所在的类必须是静态的 静态类不能实例化
2.方法也必须是静态的
3.方法的第一个参数必须是你要扩展的那个类型,比如你要给int扩展一个方法,那么第一个参数就必须是int。
4.在第一个参数前面还需要有一个this关键字。
二、扩展方法的几点总结:
1、可以向类中添加新方法,而不需要使用继承来创建新类,也不需要修改原有的类;
2、如果扩展方法与类中的方法有相同的签名,则扩展方法不会被调用,即:扩展方法会被被扩展类的同名方法覆盖,所以实现扩展方法我们需要承担随时被覆盖的风险(例如:如果扩展一个string类中的ToString(), 这时候扩展方法是无效的);
3、扩展方法不能访问被扩展类的私有成员
4、扩展方法只能使用实例来调用,不能像普通的静态方法一样使用类名调用;
5、只有引入扩展方法所在的命名空间后,扩展方法才可以使用。
public static class StringFormat
{
public static string Test(this string str)
{
return "hello";
}
public static bool IsNullOrEmpty(this string str)
{
return string.IsNullOrEmpty(str);
}
public static bool IsMatch(this string str,string pattern)
{
if (str.IsNullOrEmpty()) return false;
return Regex.IsMatch(str, pattern);
}
public static string Match(this string str,string pattern)
{
if (str.IsNullOrEmpty()) return "";
return Regex.Match(str, pattern).Value;
}
}
//-----------------------------------------------
public class Person
{
public void ShowName(string name)
{
Console.WriteLine(name);
}
}
public static class ExtendPerson
{
public static void ShowAge(this Person person,int age)
{
Console.WriteLine(age);
}
public static double ToDouble(this string str)
{
return double.Parse(str);
}
public static double ToFloat(this string str)
{
return float.Parse(str);
}
main.cs
class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.ShowAge(10);
string str = "123.123";
Console.WriteLine("toDouble-------- " + str.ToDouble());
Console.WriteLine(str.Test());
Console.WriteLine("".IsNullOrEmpty());
bool b = "123456".IsMatch(@"\d+");
string s = "123ldp615".Match("[a-zA-Z]+");
Console.WriteLine("b "+b);
Console.WriteLine("s "+s);
string value1 = "hello";
string value2 = "world";
string vv = $"say {value1} to {value2}.";
Console.WriteLine(vv);
}
}
补充一个基于object的扩展方法
class Program
{
static void Main(string[] args)
{
int a = 10;
double b = 12.111;
string c = "45";
Console.WriteLine("a: " + a.ToLocalString(a));
Console.WriteLine("b: " + b.ToLocalString(b));
Console.WriteLine("c: " + c.ToLocalString(c));
}
}
public static class Test
{
public static string ToLocalString(this object obj, object o)
{
return " --ans-- " + o.ToString();
}
public static T TestTfun<T>(this object obj)
{
return (T)obj;
}
}
参考文章:https://www.cnblogs.com/wwwzzg168/p/3749701.html
https://www.cnblogs.com/zhang1f/p/11106081.html
另:代码中提到上一篇的C#十个高级用法的部分demo代码。
tips:在项目中有一个类似Utils的工具类,里面有多个Helper,例如StringHelper、XmlHelper等等,每个Helper里面有多个static的通用方法,然后调用的时候就是StringHelper.GetNotNullStr(“aa”);这样。还有一种普通的用法就是new 一个对象,通过对象去调用类里面的非static方法。 统统可以改为扩展方法
tips:使用一个数据类,分别 n,f,str, 存储取用就可以:对象.str 对象.f 对象.n
静态类
类可以声明为 static 的,以指示它仅包含静态成员。不能使用 new 关键字创建静态类的实例。例如,创建一组不操作实例数据并且不与代码中的特定对象关联的方法是很常见的要求。您应该使用静态类来包含那些方法。
静态类的主要功能如下:
它们仅包含静态成员。----函数成员和变量都必须有static修饰
它们不能被实例化。
它们是密封的。-----------编译器编译时自动生成sealed标记
它们不能包含实例构造函数。
因此创建静态类与创建仅包含静态成员和私有构造函数的类大致一样。私有构造函数阻止类被实例化。
使用静态类的优点在于,编译器能够执行检查以确保不致偶然地添加实例成员。编译器将保证不会创建此类的实利。
静态类是密封的,因此不可被继承。静态类不能包含构造函数,但仍可声明静态构造函数以分配初始值或设置某个静态状态。