Dapper学习笔记(一)

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接口进行了扩展,然后在项目中使用的时候就可以直接使用这里写的扩展方法了。

原文地址:https://www.cnblogs.com/minesnil-forfaith/p/4587332.html