扩展方法


//扩展方法,,是一种特殊的静态方法(不能修改源代码的类,扩展方法)(Dynamic不支持扩展方法) 静态类和静态方法
//Demo1
public static class A
{
public static string Add(this string str,int a,int b)
{
return (a+b).Tostring();
}
}

string a="";
Console.WriteLine(a.Add(1,2));


//扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,//但可以像扩展类型上的实例方法一样进行调用
//可以使用扩展方法来扩展类或接口,但不能重写扩展方法。与接口或类方法具有相同名称和签名的扩展方法永远不会被调用。编译时,扩展方法的优先级总是比类型本身中定义的实例方法低

//示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 扩展方法
{
class Program
{
static void Main(string[] args)
{
string s = "Hello Extension Methods";
int i = s.WordCount();
Console.WriteLine(i);
Console.ReadKey();
}
}

public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}

原文地址:https://www.cnblogs.com/zychengzhiit1/p/4070724.html