C#擴展方法或.net擴展方法
最近在用xxxSugar時候的時候發現原生xxxSugar沒有一次能執行多條sql的方法,就想著擴展一個。不廢話,園友帶你上高速
擴展方法的定義:
在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
好比較官方的說完了,估計有的看懂了,有的沒有。莫慌,來上點干貨(博主悄悄說
下面有些點子是博主朋友提的,博主覺得還不錯就采納了朋友的建議,謝謝博主朋友提的建議)
定義:
使用:
好,放源碼
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);
完事了,

浙公網安備 33010602011771號