C#扩展方法,简单的理解是不修改原来类的源代码的情况下,为某个类添加某个方法。扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this修饰符为前缀。

有一个典型的应用场景,就是程序二开。比如别人的DLL不公开源代码,要想在DLL某个类中添加一个新方法的话,是不太可能的。但是可以使用扩展方法,达到类似的目的。

1、新建两个类文件:Rectangle、GenericClass。

    /// <summary>
/// 自定义类(长方形)
/// </summary>
public class Rectangle
{
//属性
public double Width { get; set; } = ; //宽度
public double Height { get; set; } = ; //高度 /// <summary>
/// 构造函数
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
public Rectangle (double width,double height)
{
Width = width;
Height = height;
} /// <summary>
/// 求周长
/// </summary>
/// <returns></returns>
public double GetPerimeter()
{
return (Width + Height) * ;
}
}
    /// <summary>
/// 泛型类
/// </summary>
/// <typeparam name="T"></typeparam>
public class GenericClass<T>
{
private T tobj; public GenericClass(T obj)
{
tobj = obj;
} public T GetObject()
{
return tobj;
}
}

2、新建一个WinForm程序,添加3个按钮。

3、下面就原生类String、自定义类、泛型类三种类进行扩展方法。新建一个类,命名为:ExtensionHelper。

    /// <summary>
/// 类必须是静态类,方法必须为public static类型,且参数使用this关键字。
/// </summary>
public static class ExtensionHelper
{
/// <summary>
/// 原生类String扩展方法
/// </summary>
/// <param name="str"></param>
public static void SayHello(this string str)
{
if (string.IsNullOrEmpty(str))
{
MessageBox.Show("Hello World.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(str, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
} /// <summary>
/// 自定义类扩展方法
/// </summary>
/// <param name="rect"></param>
/// <returns></returns>
public static double GetArea(this Rectangle rect)
{
return rect.Width * rect.Height;
} /// <summary>
/// 泛型类扩展方法
/// </summary>
/// <param name="gc"></param>
/// <returns></returns>
public static string Show (this GenericClass<string> gc)
{
return gc.GetObject().ToString();
}
}

4、WinForm代码如下:

        /// <summary>
/// 原生类String扩展
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
string str = "";
//string str = "Welcom to China.";
str.SayHello();
} /// <summary>
/// 自定义类扩展
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
Rectangle rect = new Rectangle(, );
MessageBox.Show("长方形的面积是:" + rect.GetArea().ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
} /// <summary>
/// 泛型类扩展
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
GenericClass<string> gc = new GenericClass<string>("这是一个泛型类扩展方法。");
MessageBox.Show(gc.Show(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

参考自:https://www.cnblogs.com/forever-Ys/p/10315830.html

C#扩展方法学习笔记的更多相关文章

  1. C#3.0扩展方法学习篇

     什么是类的扩展方法 扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型. MSDN Extension methods enable you to &q ...

  2. C#扩展方法学习

    扩展方法的本质是什么,详细见此文 C#扩展方法,爱你在心口难开 重点如下:扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型.扩展方法是一种特殊的静态方法 ...

  3. C#的扩展方法学习

    一,什么是扩展方法? 1,扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型. 2,扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用 ...

  4. zepto.1.1.6.js源码中的each方法学习笔记

    each方法接受要遍历的对象和对应的回调函数作为参数,它的作用是: 1.如果要遍历的对象是类似数组的形式(以该对象的length属性值的类型是否为number类型来判断),那么就把以要遍历的对象为执行 ...

  5. Java中关于 ArrayList 和 Map 的常用遍历方法 (学习笔记,便于以后查询)

    一.学习ArrayList与Map时,关于常用遍历方法的记录如下:  二.附源码如下: package com.study.in.myself; import java.util.ArrayList; ...

  6. Object.defineProperty()方法学习笔记

    这是js中一个非常重要的方法,ES6中某些方法的实现依赖于它,VUE通过它实现双向绑定 此方法会直接在一个对象上定义一个新属性,或者修改一个已经存在的属性, 并返回这个对象 参数 Object.def ...

  7. Android Studio调试方法学习笔记

    (注:本人所用Android Studio的Keymap已设为Eclipse copy) 1.设置断点 只有设置断点,才好定位要调试什么地方,否则找不到要调试的地方,无法调试.(调试过程中也可以增加断 ...

  8. JS数组中every(),filter(),forEach(),map(),some()方法学习笔记!

    ES5中定义了五种数组的迭代方法:every(),filter(),forEach(),map(),some(). 每个方法都接受两个参数:要在每一项运行的函数(必选)和运行该函数的作用域的对象-影响 ...

  9. dojo/dom-construct.toDom方法学习笔记

    toDom方法用来将html标签字符串转化成DOM节点.1.7之后toDom方法被分配到了dom-construct模块. require(["dojo/dom-construct" ...

随机推荐

  1. 漫谈边缘计算(三):5G的好拍档

    边缘计算的热度迅速攀升,还有一个不得不提的因素,就是5G的发展. [5G推动云计算从集中化向分布式演进] 在第一篇文章(<漫谈边缘计算(一):边缘计算是大势所趋>)中我提到,传统的云计算技 ...

  2. MySQL必知必会(汇总数据, 聚集函数)

    SELECT AVG(prod_price) AS avg_price FROM products; #AVG只能用于单个列求平均值,如想计算多个列,必须用多个AVG() SELECT AVG(pro ...

  3. SI522和RC522/ZS3801/FM17520的区别

    小编最近在测试一颗新的芯片,是国内知名厂家中科微研发的,主打超低功耗的厂家. 经过测试和比较小编发现 相对于MFRC522,SI522可以完全替换,不需要做任何更改,同时接受模式下功耗低10mA左右, ...

  4. Objective-C面试题(精心整理的,附答案)

    转自:http://www.mianwww.com/html/2014/03/20372.html 1.objective-c 是所有对象间的交互是如何实现的? 在对象间交互中每个对象承担的角色不同, ...

  5. python获取bing地图发布自己的TMS服务(一)下载瓦片

    部分结果 bing地图瓦片使用QuadKey作为命名方式. QuadKey简介 如何计算quadkey 在给定level下,把行号tileY和列号tileX转换为2进制,然后行列交叉存储,再转换为4进 ...

  6. HDU1848 Fibonacci again and again(SG 函数)

    任何一个大学生对菲波那契数列(Fibonacci numbers)应该都不会陌生,它是这样定义的: F(1)=1; F(2)=2; F(n)=F(n-1)+F(n-2)(n>=3); 所以,1, ...

  7. Where/Order by/Ggroup by/Having使用的注意事项

    1.Where.Order by.Group by .having Where作用对象是:基本表或视图,从中选出符合条件的元素. Order by 作用对象是:基本表或视图,就是排序方式,分为升序(A ...

  8. ruby 使用 rqrcode 生成二维码

    参考:  https://github.com/whomwah/rqrcode 1.  gem 'rqrcode' 2.  在helper中: require 'base64' def generat ...

  9. JS实现链式调用 a().b().c()

    function a() { this.b = function () { console.log('111') return this } this.c = function () { consol ...

  10. 【Java Web开发学习】远程方法调用RMI

    Java RMI 远程方法调用Remote Method Invocation 转载:http://www.cnblogs.com/yangchongxing/p/9078061.html 1.创建远 ...