扩展方法
来源:互联网 发布:ubuntu搭建hadoop 编辑:程序博客网 时间:2024/06/05 08:56
扩展方法实例:
扩展方法的目的就是为一个现有类型添加一个方法,现有类型既可以是int,string等数据类型,也可以是自定义的数据类型。主要是有些情况不便于在原先的方法上面直接进行修改,需求对其进行一些修饰或者在之前的基础上进行设计等,此时需要引用扩展方法。
扩展方法三要素:静态类 ,静态方法, this 关键字,
很多东西在没有使用之前是很难理解的,一些概念性的东西也比较抽象,不如直接看实例。ExterStudent作为一个扩展类可以直接在student 的实例化对象中直接调用。
Program.cs 类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExterFunction
{
class Program
{
static void Main(string[] args)
{
Student s = new Student("测试数据");
Console.WriteLine(s.ExterGetName());
Console.ReadKey();
}
}
}
student类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExterFunction
{
public class Student
{
private string _name;
public string Name {
get { return _name; }
set { _name = value; }
}
public Student(string name)
{
Name = name;
}
/// <summary>
/// 获取学生的姓名
/// </summary>
public string GetStudentName(string no)
{
return Name + no;
}
}
}
ExterStudent扩展类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExterFunction
{
public static class ExterStudent
{
public static string ExterGetName(this Student s)
{
return s.GetStudentName("002")+"这是扩展方法实现返回的数据";
}
}
}
- 扩展方法
- 扩展方法
- 扩展方法
- 扩展方法
- 扩展方法
- 扩展方法
- 扩展方法
- 扩展方法
- 扩展方法
- 扩展方法
- 扩展方法
- 扩展方法
- 扩展方法
- 扩展方法
- 扩展方法
- 扩展方法
- 扩展方法
- 扩展方法
- web编程从入门到项目实战-Babel篇
- table固定表头
- JS计算时间的加减并转换为年月日形式
- PHP搜索记住状态
- 保存 ctrl shirt 按键
- 扩展方法
- CentOS 5.5下编译安装新内核
- numpy基础操作
- Linux命令-自动挂载文件/etc/fstab功能详解[转]
- ajax 返回值的2种形式
- TableSort.js
- ScheduledExecutorService的用法
- ASP.NET Core 如何上传单个文件
- 运用正则表达式