C# 扩展方法的使用
扩展方法:是声明在非嵌套、非泛型的静态类中,为实现某种特殊功能,而为该数据类型追加的静态方法,该数据类型在形参中用this修饰。
以下是对String数据类型的扩展示例:
1、对String的扩展方法类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _Extend
{
public static class Extend
{
/// <summary>
/// 不带参数的扩展方法
/// </summary>
/// <param name="str">要扩展的数据类型</param>
/// <returns></returns>
public static int StringToInt(this string str)
{
bool r = int.TryParse(str, out int i);
if (r)
{
return i;
}
return 0;
}
/// <summary>
/// 带参数的扩展方法
/// </summary>
/// <param name="str">要扩展的数据类型</param>
/// <param name="index">参数</param>
/// <returns></returns>
public static string StringCut(this string str,int index)
{
return str.Substring(index);
}
}
}