using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1.test1
{
//原文:https://www.cnblogs.com/wolf-sun/p/4216256.html
//扩展方法,在无法修改源代码的情况下,提供了一种为该类来添加行为的方式
/*
1.定义一个静态类以包含扩展方法。 该类必须对客户端代码可见。
2.将该扩展方法实现为静态方法,并使其至少具有与包含类相同的可见性。
3.该方法的第一个参数指定方法所操作的类型;该参数必须以 this 修饰符开头。
4.在调用代码中,添加一条 using 指令以指定包含扩展方法类的命名空间。
5.按照与调用类型上的实例方法一样的方式调用扩展方法。
请注意,第一个参数不是由调用代码指定的,因为它表示正应用运算符的类型,并且编译器已经知道对象的类型。 您只需通过 n 为这两个形参提供实参。
1、扩展方法为静态方法,所在的类必须为静态类,方法第一个参数必须以this修饰符开头。
2、扩展方法在使用的时,必须能够访问到。
3、在使用时需引入扩展方法所在的命名空间。
当然你也可以直接使用要扩展的类型的命名空间,
比如string类型的命名空间为System,
你可以使用System作为StringExtension的命名空间,
这样使用的时候不需要引入命名空间了。但一般不建议这样做!
*/
public class Class6
{
public static void test1()
{
string str1 = "123";
Console.WriteLine(str1.GetBytesLength());
string str2 = "123";
Console.WriteLine(str2.GetStrJoinName("一二三"));
int id1 = 123;
Console.WriteLine(id1.GetStringFormat());
Student student1 = new Student { Name = "name1", LastName = "name2" };
Console.WriteLine("name:" + student1.GetName());
Console.WriteLine("old name:" + student1.GetLastName());
}
}
public class Student
{
public string Name { get; set; }
public string LastName { get; set; }
public string GetName()
{
return this.Name;
}
}
//Student 扩展
public static class StudentExt
{
public static string GetLastName(this Student source)
{
return source.LastName;
}
}
//int 扩展
public static class IntExtension
{
public static string GetStringFormat(this int source)
{
return "字符串格式:" + source.ToString();
}
}
//string 扩展
public static class StringExtension
{
//获取字符串的字节数
public static int GetBytesLength(this string source)
{
byte[] bytes = Encoding.Default.GetBytes(source);
return bytes.Length;
}
//字符串连接
public static string GetStrJoinName(this string source, string name)
{
return source + " 连接 " + name;
}
}
}