Dapper學習筆記(一)

來源:互聯網
上載者:User

標籤:

https://github.com/StackExchange/dapper-dot-net

Dapper是對IDbConnection的擴充,需要使用Dapper提供的擴充只需要把SqlMapper這個檔案放到自己的項目中即可。這樣項目中的IDbConnection就可以直接使用Dapper中的擴充方法,這是怎麼實現的呢?百度才知道這個是C#提供的擴充方法。

擴充方法如何使用呢?直接看代碼。

對Object寫一個自訂的ToString()方法,輸出"自訂Object的ToString()方法"

public static string ToString(this Object s,int a)
{
return "自訂Object的ToString()方法";
}

方法必須為靜態方法,參數必須以this為首碼,然後接下來就是需要擴充的類。這裡加上一個int a參數是假如因為自訂的擴充方法和原有的方法具有相同的名稱和參數,那麼永遠不會調用自訂的擴充方法。

擴充方法還可以給自己建立的類進行擴充,比如這樣使用

建立一個自訂類MyClass

public class MyClass
{

}

對MyClass增加擴充方法,輸出類的全名

public static string ToMyClassName(this MyClass c)
{
    return c.GetType().FullName.ToString();
}

這樣  

MyClass my = new MyClass();
System.Console.WriteLine("我自訂的類" + my.ToMyClassName());

將會直接輸出"我自訂的類Simple.Console.MyClass"

附上案例代碼

using System;namespace Simple.Console{    public class MyClass    {    }    public static class Extension//必須先聲明一個靜態類,類名隨意    {        public static string ToMyWord(this String str)//擴建的方法必須是靜態方法,參數裡面必須含有this關鍵字,this關鍵字後面的類型為需要擴充的類型        {            return "這是我自訂的string擴充方法";        }        public static string ToCurentTime(this DateTime dt)        {            return DateTime.Now.ToLongDateString();        }        public static string ToMyClassName(this MyClass c)        {            return c.GetType().FullName.ToString();        }        public static string ToString(this Object s,int a)        {            return "自訂Object的ToString()方法";        }    }    class Program    {        static void Main(string[] args)        {            MyClass my = new MyClass();            System.Console.WriteLine("我自訂的類" + my.ToMyClassName());            System.Console.WriteLine("我自訂的String擴充方法" + "我們".ToMyWord());            System.Console.WriteLine("我自訂的DateTime擴充方法" + new DateTime().ToCurentTime());            System.Console.WriteLine("我自訂的重寫ToString方法" + my.ToString(1));            System.Console.ReadLine();        }    }}
View Code

輸出結果

  最後看下SqlMapper.cs中的代碼

1 /// <summary>2         /// Execute parameterized SQL  3         /// </summary>4         /// <returns>Number of rows affected</returns>5         public static int Execute(this IDbConnection cnn, CommandDefinition command)6         {7             return ExecuteImpl(cnn, ref command);8         }
View Code

這下就知道原來這個方式是對IDbConnection介面進行了擴充,然後在項目中使用的時候就可以直接使用這裡寫的擴充方法了。

 

Dapper學習筆記(一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.