C#扩展方法或.net扩展方法

最近在用xxxSugar时候的时候发现原生xxxSugar没有一次能执行多条sql的方法,就想着扩展一个。不废话,园友带你上高速hahahaha

 

扩展方法的定义:

在C#中,扩展方法是一种静态方法,它被用来向现有的类型添加新方法,而不需要修改原始类型定义或继承原有类型。扩展方法通常用于封装额外的功能,或者在第三方库的类型上添加功能。

要定义一个扩展方法,你需要遵循以下步骤:

1. 使用 static 关键字

扩展方法必须是静态的。

2. 使用 this 关键字

在第一个参数前使用 this 关键字,并且这个参数的类型必须是在同一个类定义之外的。这表明你想要为这个类型扩展方法。

3. 定义方法

在方法的参数列表中,除了 this 关键字指定的参数外,还可以有其他的参数。

示例代码

假设你有一个 String 类型的扩展方法,用来检查字符串是否为空或者只包含空白字符。

using System;

public static class StringExtensions
{
  public static bool IsNullOrWhiteSpace(this string str)
  {
    if (str == null) return true;
    foreach (char c in str)
    {
      if (!char.IsWhiteSpace(c)) return false;
    }
    return true;
  }
}

 

使用扩展方法

一旦你定义了扩展方法,你就可以像使用其他任何实例方法一样使用它:

string testString = " "; // 仅包含空格的字符串
bool result = testString.IsNullOrWhiteSpace(); // 使用扩展方法
Console.WriteLine(result); // 输出:True

 

好比较官方的说完了,估计有的看懂了,有的没有。莫慌,来上点干货(博主悄悄说xu下面有些点子是博主朋友提的,博主觉得还不错就采纳了朋友的建议,谢谢博主朋友提的建议)

定义:image 

 

使用:image

 

 

好,放源码

 

 

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


namespace SqlSugar;


/// <summary>
/// SqlSugar.IAdo扩展方法
/// </summary>
public static class IAdoExtensions
{
  /// <summary>
  /// 执行sql批处理
  /// </summary>
  /// <param name="ado">sqlSugarClient的ado对象</param>
  /// <param name="sqlList">要执行的sql的IEnumerable集合</param>
  /// <returns></returns>
  public static int ExecuteSqlBatch(this IAdo ado, IEnumerable<string> sqlList)
  {
    ado.BeginTran();
    try
    {
      foreach (string sql in sqlList)
      {
        // 执行每条SQL语句
        int result = ado.ExecuteCommand(sql);

        if (result == -1)
        {
          return 0;

        }
      }
      // 提交事务
      ado.CommitTran();//.CommitTransaction();
      return 1;

    }
    catch (Exception ex)

    {
      // 发生异常,回滚事务
      ado.RollbackTran();
      return 0;
    }
  }

}

 

/// <summary>
/// 要执行的sqlList
/// </summary>
List<string> SqlList = new List<string>();

int result = sqlSugarClient.Ado.ExecuteSqlBatch(SqlList);

 

完事了,nazoubuxie

 

 

 

如需转载或引用请标明出处!本号发布的包括但不限于学术论文、科研成果、研究资料等,仅供内部学习、学术交流所使用,不得用于任何商业用途或牟利,特此声明!

posted @ 2025-10-14 16:34  黑夜管理员  阅读(21)  评论(0)    收藏  举报