.NET 增加扩展方法

声明:通过一个js的实例来告诉你C#也可以实现这样的效果。

在JS中是这样实现的:

你是否见过JS中给系统默认Array对象增加一个自定义查重方法contains

在没有给Array原型上增加contains之前,通过vs编辑器是无法通过点的方式来调用contains

 

.NET 增加扩展方法_第1张图片

当给Array原型上增加contains之后,便可以通过点的方式进行调用

.NET 增加扩展方法_第2张图片

 

在C#中是这样实现的:

需求:我们要在String对象上增加一个ToString2()的函数

在没有给String对象增加ToString2()之前是无法通过点来调用ToString2()函数,下图是无法找到ToString2()函数

.NET 增加扩展方法_第3张图片

当增加了扩展函数后便可以通过点的方式来调用扩展函数

.NET 增加扩展方法_第4张图片

语法:定义扩展方法,它必须是一个静态类static,并且要使用this关键字来修饰要对那个对象进行操作。以上重点和最终效果均用红线标注。

实现代码:

1.新建一个StringExtension类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace Helper {
    public static class StringExtension {
        public static String ToString2(this string s) {
            return s+" by-师傅";
        }
    }
}

2.在页面(Default.aspx)上面调用

<%@ Page Language="C#" %>
<%--需要引入扩展类的命名空间--%>
<%@ Import Namespace="Helper" %>
<%
    string res = string.Empty;
    string str = "我是字符串";
    res = str.ToString2();
    Response.Write(res);
    //最终输出:我是字符串 by-师傅
%>

 

你学会了吗?是不是逼格满满?

转载于:https://www.cnblogs.com/shifubug/p/10604805.html

你可能感兴趣的:(c#)