扩展方法是一种参数化类型。它总是用于静态类。此方法中定义的第一个变量始终是“this”关键字。扩展方法是一种特殊的静态方法,但它们被调用时就像它们是扩展类型上的实例方法一样。扩展方法是一种特殊的静态方法,它允许您向现有类型添加新方法,而无需创建派生类型。扩展方法实际上可以扩展String类来直接支持它。您可以通过使用一组静态方法定义一个静态类来实现,这些静态方法将成为您的扩展方法库。扩展方法允许在不依赖继承或者不必更改类源代码的情况下扩展现有类。这意味着,如果您想将一些方法添加到现有的String类中,您可以很容易地做到这一点。
C#中的扩展方法示例
- 首先在应用程序中添加一个类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ext_method
{
static class Tom
{
public static int sum(this int a, int b)
{
int c = a + b;
return c;
}
public static int sub(this int a, int b)
{
int c = a - b;
return c;
}
public static int mul(this int a, int b)
{
int c = a * b;
return c;
}
public static int div(this int a, int b)
{
int c = a/b;
return c;
}
}
}
- 然后在页面lede_event上写代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Ext_method
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int a = 10, b = 5;
private void Form1_Load(object sender, EventArgs e) {
int c = b.sum(a);
int c1 = b.sub(a);
int c2 = b.mul(a);
int c3 = b.div(a);
textBox1.Text = c.ToString();
textBox2.Text = c1.ToString();
textBox3.Text = c2.ToString();
textBox4.Text = c3.ToString();
}
}
}
这是扩展方法的一个简单示例,我们知道需要创建类的对象。
我们在参数的另一个地方使用了类,但无需创建类的对象。
日期:2020-04-11 22:50:29 来源:oir作者:oir
