搜索
您的当前位置:首页正文

C#之扩展类,提供附加属性

来源:尚车旅游网

C#之扩展类,提供附加属性

为现有非静态变量类型添加新方法。
作用:提升程序拓展性,不需要在对象中重新写方法,不需要通过继承来添加方法,为别人封装的类型写额外的方法。

1.声明为静态类

public static class StringExtensions

2.声明公共静态方法(扩展方法是一种静态方法)

3.第一个参数必须是this 第二个参数必须是扩展对象,第三个参数代表使用该方法的实例化对象

public static string ReverseString(this string s)

4.第三个参数之后可以有任意多个额外参数。

public static void SpeakStringInfo(this string str,string str2,string str3)
string str="p1";
str.SpeakString("p2","p3");
``

```c
    /// <summary>
    /// 为Form1注入一个方法
    /// </summary>
    public static class MyFormExt
    {
        public static void Test(this Form1 form1)
        {
            MessageBox.Show("扩展Form类");
        }
    }

实例1

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp11
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Form1 form1 = new Form1();
            form1.Test();
        }
    }

    /// <summary>
    /// 为Form1注入一个方法
    /// </summary>
    public static class MyFormExt
    {
        public static void Test(this Form1 form1)
        {
            MessageBox.Show("扩展Form类");
        }
    }



}

实例2




public static class StringExtensions
{
    // 扩展方法
    public static string ReverseString(this string s)
    {
        char[] charArray = s.ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }
}
 
// 使用扩展方法
class Program
{
    static void Main(string[] args)
    {
        string originalString = "Hello";
        string reversedString = originalString.ReverseString();
        Console.WriteLine(reversedString); // 输出 "olleH"
    }
}


在这个例子中,StringExtensions 类包含了一个静态方法 ReverseString,它将字符串反转。通过使用 this 关键字,我们可以像调用实例方法一样调用这个静态方法。在 Main 方法中,我们创建了一个字符串并使用 ReverseString 方法将其反转。

因篇幅问题不能全部显示,请点此查看更多更全内容

Top