>

世袭类实例云顶娱乐yd2221:,基于Dapper叁回封装

- 编辑:云顶娱乐yd2221 -

世袭类实例云顶娱乐yd2221:,基于Dapper叁回封装

数字信号的定义

实信号(signal卡塔尔--     进程之间通信的秘籍,是风度翩翩种软件中断。叁个历程后生可畏旦接纳到确定性信号就可以卡住原本的程序试行流程来拍卖时域信号。

多少个常用确定性信号:

SIGINT     终止进度  中断进程  (control+c)

SIGTERM   终止进程     软件终止时域信号

SIGKILL   终止进度     杀死进程

SIGALRM 时钟实信号

 

世家恐怕在编码中或多或少的运用过out的ref,可是是或不是注意过她两的事必躬亲用法以至界别?

黄金年代、先看看效果

基于Dapper二回封装了二个易用的ORM工具类:SqlDapperUtil,把常备能用到的各样CRUD都进行了简化封装,让平时程序员只需关心业务即可,因为特别轻巧,故直接贴源代码,大家若需使用能够平素复制到项目中,该SqlDapperUtil已大规模用于公司项目中。

在存活类(基类、父类)上树立新类(派生类、子类)的管理进度称为世襲。派生类能自动获取基类的除了构造函数和析构函数以外的具有成员,能够在派生类中增添新的品质和办法扩大其效果。

经过甘休功率信号 SIGTERM和SIGKILL的不一致

SIGTERM相比和睦,进度能捕捉这些复信号,依据你的内需来关闭程序。在关闭程序以前,您可以为止展开的记录文件和完毕正在做的天职。在一些意况下,假使进度正在开展学业何况不可能暂停,那么进程能够忽视那个SIGTERM非确定性信号。

对于SIGKILL时域信号,进度是不能不理的。那是一个 “我随意你在做哪些,立时终止”的时域信号。纵然你发送SIGKILL时域信号给进度,Linux就将经过截至在此。

 

正文想介绍下详细介绍下out参数,ref参数以致日常值参数。

云顶娱乐yd2221 1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data;
using System.Data.Common;
using System.Reflection;
using System.IO;
using System.Collections.Concurrent;
using System.Data.SqlClient;

namespace Zuowj.Common
{
    /// <summary>
    /// 基于Dapper的数据操作类封装的工具类
    /// Author:左文俊
    /// Date:2017/12/11
    /// </summary>
    public class SqlDapperUtil
    {
        private static string dbConnectionStringConfigPath = null;
        private readonly static ConcurrentDictionary<string, bool> dbConnNamesCacheDic = new ConcurrentDictionary<string, bool>();

        private string dbConnectionName = null;
        private string dbConnectionString = null;
        private string dbProviderName = null;
        private IDbConnection dbConnection = null;
        private bool useDbTransaction = false;
        private IDbTransaction dbTransaction = null;


        #region 私有方法

        private IDbConnection GetDbConnection()
        {
            bool needCreateNew = false;
            if (dbConnection == null || string.IsNullOrWhiteSpace(dbConnection.ConnectionString))
            {
                needCreateNew = true;
            }
            else if (!MemoryCacheUtil.Contains(dbConnectionName))
            {
                needCreateNew = true;
            }

            if (needCreateNew)
            {
                dbConnectionString = GetDbConnectionString(dbConnectionName, out dbProviderName);
                var dbProviderFactory = DbProviderFactories.GetFactory(dbProviderName);
                dbConnection = dbProviderFactory.CreateConnection();
                dbConnection.ConnectionString = dbConnectionString;
            }

            if (dbConnection.State == ConnectionState.Closed)
            {
                dbConnection.Open();
            }

            return dbConnection;
        }

        private string GetDbConnectionString(string dbConnName, out string dbProviderName)
        {
            //如果指定的连接字符串配置文件路径,则创建缓存依赖,一旦配置文件更改就失效,再重新读取
            string[] connInfos = MemoryCacheUtil.GetOrAddCacheItem(dbConnName, () =>
            {
                var connStrSettings = ConfigUtil.GetConnectionStringForConfigPath(dbConnName, SqlDapperUtil.DbConnectionStringConfigPath);
                string dbProdName = connStrSettings.ProviderName;
                string dbConnStr = connStrSettings.ConnectionString;
                //LogUtil.Info(string.Format("SqlDapperUtil.GetDbConnectionString>读取连接字符串配置节点[{0}]:{1},ProviderName:{2}", dbConnName, dbConnStr, dbProdName), "SqlDapperUtil.GetDbConnectionString");
                return new[] { EncryptUtil.Decrypt(dbConnStr), dbProdName };
            }, SqlDapperUtil.DbConnectionStringConfigPath);

            dbProviderName = connInfos[1];
            return connInfos[0];
        }


        private T UseDbConnection<T>(Func<IDbConnection, T> queryOrExecSqlFunc)
        {
            IDbConnection dbConn = null;

            try
            {
                Type modelType = typeof(T);
                var typeMap = Dapper.SqlMapper.GetTypeMap(modelType);
                if (typeMap == null || !(typeMap is ColumnAttributeTypeMapper<T>))
                {
                    Dapper.SqlMapper.SetTypeMap(modelType, new ColumnAttributeTypeMapper<T>());
                }

                dbConn = GetDbConnection();
                if (useDbTransaction && dbTransaction == null)
                {
                    dbTransaction = GetDbTransaction();
                }

                return queryOrExecSqlFunc(dbConn);
            }
            catch
            {
                throw;
            }
            finally
            {
                if (dbTransaction == null && dbConn != null)
                {
                    CloseDbConnection(dbConn);
                }
            }
        }

        private void CloseDbConnection(IDbConnection dbConn, bool disposed = false)
        {
            if (dbConn != null)
            {
                if (disposed && dbTransaction != null)
                {
                    dbTransaction.Rollback();
                    dbTransaction.Dispose();
                    dbTransaction = null;
                }

                if (dbConn.State != ConnectionState.Closed)
                {
                    dbConn.Close();
                }
                dbConn.Dispose();
                dbConn = null;
            }
        }

        /// <summary>
        /// 获取一个事务对象(如果需要确保多条执行语句的一致性,必需使用事务)
        /// </summary>
        /// <param name="il"></param>
        /// <returns></returns>
        private IDbTransaction GetDbTransaction(IsolationLevel il = IsolationLevel.Unspecified)
        {
            return GetDbConnection().BeginTransaction(il);
        }

        private DynamicParameters ToDynamicParameters(Dictionary<string, object> paramDic)
        {
            return new DynamicParameters(paramDic);
        }

        #endregion

        public static string DbConnectionStringConfigPath
        {
            get
            {
                if (string.IsNullOrEmpty(dbConnectionStringConfigPath))//如果没有指定配置文件,则取默认的配置文件路径作为缓存依赖路径
                {
                    dbConnectionStringConfigPath = BaseUtil.GetConfigPath();
                }

                return dbConnectionStringConfigPath;
            }
            set
            {
                if (!string.IsNullOrWhiteSpace(value) && !File.Exists(value))
                {
                    throw new FileNotFoundException("指定的DB连接字符串配置文件不存在:" + value);
                }

                //如果配置文件改变,则可能导致连接字符串改变,故必需清除所有连接字符串的缓存以便后续重新加载字符串
                if (!string.Equals(dbConnectionStringConfigPath, value, StringComparison.OrdinalIgnoreCase))
                {
                    foreach (var item in dbConnNamesCacheDic)
                    {
                        MemoryCacheUtil.RemoveCacheItem(item.Key);
                    }
                }

                dbConnectionStringConfigPath = value;
            }
        }

        public SqlDapperUtil(string connName)
        {
            dbConnectionName = connName;
            if (!dbConnNamesCacheDic.ContainsKey(connName)) //如果静态缓存中没有,则加入到静态缓存中
            {
                dbConnNamesCacheDic[connName] = true;
            }

        }


        /// <summary>
        /// 使用事务
        /// </summary>
        public void UseDbTransaction()
        {
            useDbTransaction = true;
        }


        /// <summary>
        /// 获取一个值,param可以是SQL参数也可以是匿名对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <param name="transaction"></param>
        /// <param name="commandTimeout"></param>
        /// <param name="commandType"></param>
        /// <returns></returns>
        public T GetValue<T>(string sql, object param = null, int? commandTimeout = null, CommandType? commandType = null)
        {
            return UseDbConnection((dbConn) =>
             {
                 return dbConn.ExecuteScalar<T>(sql, param, dbTransaction, commandTimeout, commandType);
             });
        }

        /// <summary>
        /// 获取第一行的所有值,param可以是SQL参数也可以是匿名对象
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <param name="transaction"></param>
        /// <param name="commandTimeout"></param>
        /// <param name="commandType"></param>
        /// <returns></returns>
        public Dictionary<string, dynamic> GetFirstValues(string sql, object param = null, int? commandTimeout = null, CommandType? commandType = null)
        {
            return UseDbConnection((dbConn) =>
            {
                Dictionary<string, dynamic> firstValues = new Dictionary<string, dynamic>();
                List<string> indexColNameMappings = new List<string>();
                int rowIndex = 0;
                using (var reader = dbConn.ExecuteReader(sql, param, dbTransaction, commandTimeout, commandType))
                {
                    while (reader.Read())
                    {
                        if ((++rowIndex) > 1) break;
                        if (indexColNameMappings.Count == 0)
                        {
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                indexColNameMappings.Add(reader.GetName(i));
                            }
                        }

                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            firstValues[indexColNameMappings[i]] = reader.GetValue(i);
                        }
                    }
                    reader.Close();
                }

                return firstValues;

            });
        }

        /// <summary>
        /// 获取一个数据模型实体类,param可以是SQL参数也可以是匿名对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <param name="transaction"></param>
        /// <param name="commandTimeout"></param>
        /// <param name="commandType"></param>
        /// <returns></returns>
        public T GetModel<T>(string sql, object param = null, int? commandTimeout = null, CommandType? commandType = null) where T : class
        {
            return UseDbConnection((dbConn) =>
            {
                return dbConn.QueryFirstOrDefault<T>(sql, param, dbTransaction, commandTimeout, commandType);
            });
        }

        /// <summary>
        /// 获取符合条件的所有数据模型实体类列表,param可以是SQL参数也可以是匿名对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <param name="transaction"></param>
        /// <param name="buffered"></param>
        /// <param name="commandTimeout"></param>
        /// <param name="commandType"></param>
        /// <returns></returns>
        public List<T> GetModelList<T>(string sql, object param = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null) where T : class
        {
            return UseDbConnection((dbConn) =>
            {
                return dbConn.Query<T>(sql, param, dbTransaction, buffered, commandTimeout, commandType).ToList();
            });
        }

        /// <summary>
        /// 获取符合条件的所有数据并根据动态构建Model类委托来创建合适的返回结果(适用于临时性结果且无对应的模型实体类的情况)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="buildModelFunc"></param>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <param name="buffered"></param>
        /// <param name="commandTimeout"></param>
        /// <param name="commandType"></param>
        /// <returns></returns>
        public T GetDynamicModel<T>(Func<IEnumerable<dynamic>, T> buildModelFunc, string sql, object param = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
        {
            var dynamicResult = UseDbConnection((dbConn) =>
           {
               return dbConn.Query(sql, param, dbTransaction, buffered, commandTimeout, commandType);
           });

            return buildModelFunc(dynamicResult);
        }

        /// <summary>
        /// 获取符合条件的所有指定返回结果对象的列表(复合对象【如:1对多,1对1】),param可以是SQL参数也可以是匿名对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="types"></param>
        /// <param name="map"></param>
        /// <param name="param"></param>
        /// <param name="transaction"></param>
        /// <param name="buffered"></param>
        /// <param name="splitOn"></param>
        /// <param name="commandTimeout"></param>
        /// <param name="commandType"></param>
        /// <returns></returns>

        public List<T> GetMultModelList<T>(string sql, Type[] types, Func<object[], T> map, object param = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null)
        {
            return UseDbConnection((dbConn) =>
            {
                return dbConn.Query<T>(sql, types, map, param, dbTransaction, buffered, splitOn, commandTimeout, commandType).ToList();
            });
        }




        /// <summary>
        /// 执行SQL命令(CRUD),param可以是SQL参数也可以是要添加的实体类
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <param name="transaction"></param>
        /// <param name="commandTimeout"></param>
        /// <param name="commandType"></param>
        /// <returns></returns>
        public bool ExecuteCommand(string sql, object param = null, int? commandTimeout = null, CommandType? commandType = null)
        {
            return UseDbConnection((dbConn) =>
            {
                int result = dbConn.Execute(sql, param, dbTransaction, commandTimeout, commandType);
                return (result > 0);
            });
        }

        /// <summary>
        /// 批量转移数据(利用SqlBulkCopy实现快速大批量插入到指定的目的表及SqlDataAdapter的批量删除)
        /// </summary>
        public bool BatchMoveData(string srcSelectSql, string srcTableName, List<SqlParameter> srcPrimarykeyParams, string destConnName, string destTableName)
        {

            using (SqlDataAdapter srcSqlDataAdapter = new SqlDataAdapter(srcSelectSql, GetDbConnectionString(dbConnectionName, out dbProviderName)))
            {
                DataTable srcTable = new DataTable();
                SqlCommand deleteCommand = null;
                try
                {
                    srcSqlDataAdapter.AcceptChangesDuringFill = true;
                    srcSqlDataAdapter.AcceptChangesDuringUpdate = false;
                    srcSqlDataAdapter.Fill(srcTable);

                    if (srcTable == null || srcTable.Rows.Count <= 0) return true;

                    string notExistsDestSqlWhere = null;
                    string deleteSrcSqlWhere = null;

                    for (int i = 0; i < srcPrimarykeyParams.Count; i++)
                    {
                        string keyColName = srcPrimarykeyParams[i].ParameterName.Replace("@", "");
                        notExistsDestSqlWhere += string.Format(" AND told.{0}=tnew.{0}", keyColName);
                        deleteSrcSqlWhere += string.Format(" AND {0}=@{0}", keyColName);
                    }

                    string dbProviderName2 = null;
                    using (var destConn = new SqlConnection(GetDbConnectionString(destConnName, out dbProviderName2)))
                    {
                        destConn.Open();

                        string tempDestTableName = "#temp_" + destTableName;
                        destConn.Execute(string.Format("select top 0 * into {0} from {1}", tempDestTableName, destTableName));
                        string destInsertCols = null;
                        using (var destSqlBulkCopy = new SqlBulkCopy(destConn))
                        {
                            try
                            {
                                destSqlBulkCopy.BulkCopyTimeout = 120;
                                destSqlBulkCopy.DestinationTableName = tempDestTableName;
                                foreach (DataColumn col in srcTable.Columns)
                                {
                                    destSqlBulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
                                    destInsertCols += "," + col.ColumnName;
                                }

                                destSqlBulkCopy.BatchSize = 1000;
                                destSqlBulkCopy.WriteToServer(srcTable);
                            }
                            catch (Exception ex)
                            {
                                //LogUtil.Error("SqlDapperUtil.BatchMoveData.SqlBulkCopy:" + ex.ToString(), "SqlDapperUtil.BatchMoveData");
                            }

                            destInsertCols = destInsertCols.Substring(1);

                            destConn.Execute(string.Format("insert into {1}({0}) select {0} from {2} tnew where not exists(select 1 from {1} told where {3})",
                                             destInsertCols, destTableName, tempDestTableName, notExistsDestSqlWhere.Trim().Substring(3)), null, null, 100);
                        }
                        destConn.Close();
                    }

                    deleteCommand = new SqlCommand(string.Format("DELETE FROM {0} WHERE {1}", srcTableName, deleteSrcSqlWhere.Trim().Substring(3)), srcSqlDataAdapter.SelectCommand.Connection);
                    deleteCommand.Parameters.AddRange(srcPrimarykeyParams.ToArray());
                    deleteCommand.UpdatedRowSource = UpdateRowSource.None;
                    deleteCommand.CommandTimeout = 200;

                    srcSqlDataAdapter.DeleteCommand = deleteCommand;
                    foreach (DataRow row in srcTable.Rows)
                    {
                        row.Delete();
                    }

                    srcSqlDataAdapter.UpdateBatchSize = 1000;
                    srcSqlDataAdapter.Update(srcTable);
                    srcTable.AcceptChanges();

                    return true;
                }
                catch (Exception ex)
                {
                    //LogUtil.Error("SqlDapperUtil.BatchMoveData:" + ex.ToString(), "SqlDapperUtil.BatchMoveData");
                    return false;
                }
                finally
                {
                    if (deleteCommand != null)
                    {
                        deleteCommand.Parameters.Clear();
                    }
                }
            }

        }

        /// <summary>
        /// 批量复制数据(把源DB中根据SQL语句查出的结果批量COPY插入到目的DB的目的表中)
        /// </summary>
        public TResult BatchCopyData<TResult>(string srcSelectSql, string destConnName, string destTableName, IDictionary<string, string> colMappings, Func<IDbConnection, TResult> afterCoppyFunc)
        {

            using (SqlDataAdapter srcSqlDataAdapter = new SqlDataAdapter(srcSelectSql, GetDbConnectionString(dbConnectionName, out dbProviderName)))
            {
                DataTable srcTable = new DataTable();
                TResult copyResult = default(TResult);
                try
                {
                    srcSqlDataAdapter.AcceptChangesDuringFill = true;
                    srcSqlDataAdapter.AcceptChangesDuringUpdate = false;
                    srcSqlDataAdapter.Fill(srcTable);

                    if (srcTable == null || srcTable.Rows.Count <= 0) return copyResult;


                    string dbProviderName2 = null;
                    using (var destConn = new SqlConnection(GetDbConnectionString(destConnName, out dbProviderName2)))
                    {
                        destConn.Open();
                        string tempDestTableName = "#temp_" + destTableName;
                        destConn.Execute(string.Format("select top 0 * into {0} from {1}", tempDestTableName, destTableName));
                        bool bcpResult = false;
                        using (var destSqlBulkCopy = new SqlBulkCopy(destConn))
                        {
                            try
                            {
                                destSqlBulkCopy.BulkCopyTimeout = 120;
                                destSqlBulkCopy.DestinationTableName = tempDestTableName;
                                foreach (var col in colMappings)
                                {
                                    destSqlBulkCopy.ColumnMappings.Add(col.Key, col.Value);
                                }

                                destSqlBulkCopy.BatchSize = 1000;
                                destSqlBulkCopy.WriteToServer(srcTable);
                                bcpResult = true;
                            }
                            catch (Exception ex)
                            {
                                //LogUtil.Error("SqlDapperUtil.BatchMoveData.SqlBulkCopy:" + ex.ToString(), "SqlDapperUtil.BatchMoveData");
                            }
                        }

                        if (bcpResult)
                        {
                            copyResult = afterCoppyFunc(destConn);
                        }

                        destConn.Close();
                    }

                    return copyResult;
                }
                catch (Exception ex)
                {
                    //LogUtil.Error("SqlDapperUtil.BatchCopyData:" + ex.ToString(), "SqlDapperUtil.BatchCopyData");
                    return copyResult;
                }
            }

        }


        /// <summary>
        /// 当使用了事务,则最后需要调用该方法以提交所有操作
        /// </summary>
        /// <param name="dbTransaction"></param>
        public void Commit()
        {
            try
            {
                if (dbTransaction.Connection != null && dbTransaction.Connection.State != ConnectionState.Closed)
                {
                    dbTransaction.Commit();
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (dbTransaction.Connection != null)
                {
                    CloseDbConnection(dbTransaction.Connection);
                }
                dbTransaction.Dispose();
                dbTransaction = null;
                useDbTransaction = false;

                if (dbConnection != null)
                {
                    CloseDbConnection(dbConnection);
                }
            }
        }

        /// <summary>
        /// 当使用了事务,如果报错或需要中断执行,则需要调用该方法执行回滚操作
        /// </summary>
        /// <param name="dbTransaction"></param>
        public void Rollback()
        {
            try
            {
                if (dbTransaction.Connection != null && dbTransaction.Connection.State != ConnectionState.Closed)
                {
                    dbTransaction.Rollback();
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (dbTransaction.Connection != null)
                {
                    CloseDbConnection(dbTransaction.Connection);
                }

                dbTransaction.Dispose();
                dbTransaction = null;
                useDbTransaction = false;
            }
        }

        ~SqlDapperUtil()
        {
            try
            {
                CloseDbConnection(dbConnection, true);
            }
            catch
            { }
        }

    }
}

三翻五次的风味:

出殡时域信号平时有三种原因:

1(被动式)  内核检查测验到一个类别事件.比方子进程退出会像父进度发送SIGCHLD时限信号.键盘按下control+c会发送SIGINT时限信号

2(主动式)  通过系统调用kill来向钦命进度发送时限信号

 

 

操作系统规定了经过收到频域信号之后的暗中认可行为

然则,大家能够通过绑定非频域信号管理函数来改进进程收到时限信号之后的作为

有三个时限信号是不行改变的SIGTOP和SIGKILL

绑定功率信号管理函数:

 

  1.  

    import os

  2.  

    import signal

  3.  

    from time import sleep

  4.  

     

  5.  

    def onsignal_term(a,b):

  1.  

    print '收到SIGTERM信号'

  2.  

     

  3.  

    #此处是绑定时域信号管理函数,将SIGTERM绑定在函数onsignal_term上面

  1.  

    signal.signal(signal.SIGTERM,onsignal_term)

  2.  

     

  3.  

    def onsignal_usr1(a,b):

  1.  

    print '收到SIGUSR1信号'

  2.  

    #此地是绑定能量信号管理函数,将SIGUSLacrosse1绑定在函数onsignal_term上面

  1.  

    signal.signal(signal.SIGUSR1,onsignal_usr1)

  2.  

     

  3.  

    while 1:

  1.  

    print '小编的进程id是',os.getpid()

  2.  

    sleep(10)

 

运作该程序。然后经过此外二个经过来发送实信号。

出殡音信的代码如下:

  1.  

    import os

  2.  

    import signal

  3.  

     

  4.  

    #出殡数字信号,16175是眼下那一个绑定实信号管理函数的pid,须求活动改良

  1.  

    os.kill(16175,signal.SIGTERM)

  2.  

    #发送随机信号,16175是前边那几个绑定随机信号管理函数的pid,要求活动改善

  1.  

    os.kill(16175,signal.SIGUSR1)

值参数

在运用参数时,把二个值传递给函数使用的三个变量。在函数中对此变量的其余改革都不影响函数调用中钦定的参数。如下边包车型地铁函数,是使函数是使传递过来的参数值加倍,并展示出来:

 static void ShowDouble(int num)
        {
            num = num * 2;
            Console.WriteLine("num*2={0}", num);
        }

参数num在函数中被加倍,假诺按以下办法调用它:

            int num = 5;
            Console.WriteLine("num={0}", num);
            ShowDouble(num);
            Console.WriteLine("num={0}", num);

输出到调整台的文件如下所示:

云顶娱乐yd2221 2

把num作为参数,调用ShowDouble()并不影响Mian()中num的值,纵然把num值加倍之后再赋值给num,在函数调用完事后num的值依然不会变。

那也没怎么难题。

只是借使大家想改动num的值吗?我们会想到利用为num再次来到新值的函数:

 static int DoubleNum(int num)
        {
            num = num * 2;
            return num;
        }

下一场调用:

            int num = 5;
            Console.WriteLine("num={0}", num);
            num = DoubleNum(num);
            Console.WriteLine("num={0}", num);

这段代码不是很直观,且不能够校正当作参数的四个变量值(因为函数独有三个重返值卡塔 尔(阿拉伯语:قطر‎。那个时候我们得以想到援引参数,即函数管理的变量和函数调用的变量雷同,而不光是值相同的变量。因而对那些变量的别的变动都会影响用作参数的变量值。为此,我们采纳ref关键词钦赐参数。

 

世袭类实例云顶娱乐yd2221:,基于Dapper叁回封装了一个易用的ORM工具类。ColumnAttributeTypeMapper协助类相关代码如下:(假若不思量实体类的属性与表字段不相通的情况,如下映射类能够无需加上,同期SqlDapperUtil中移除相关注重ColumnAttributeTypeMapper逻辑就能够)

可传递性:C从B派生,B从A派生,那么C不唯有世袭B也世襲A。

利用复信号须要特别注意的地点:

假定三个经过收到三个SIGUSCRUISER1实信号,然后实践复信号绑定函数,第贰个SIGUS酷威2能量信号又来了,第叁个实信号未有被管理完成的话,第一个频限信号就能够放弃。

故而,尽量不要在四线程中运用实信号。

以此不妥,测量检验没觉察有非确定性信号遗失

事例演示:

收纳功率信号的程序,你会意识只要有其余风流倜傥端采取多线程向那几个进程发送实信号,会挂大器晚成漏万一些实信号。

 

ref参数

            int num = 5;
            Console.WriteLine("num={0}", num);
            ShowDouble(ref num);
            Console.WriteLine("num={0}", num);

运维调整台结果如下:

云顶娱乐yd2221 3

用作ref的参数的变量有四个约束:

1.函数大概会变动引用参数的值,所以必得在函数调用中使用“特别量”变量,所以上边包车型地铁代码是不被允许的:

 

            const int num = 5;
            Console.WriteLine("num={0}", num);
            ShowDouble(ref num);
            Console.WriteLine("num={0}", num);

2.必须利用开端化过的变量。C#不允许假定ref参数在函数调用时开始化,下边包车型客车代码也是不被允许的:

            int num;
            Console.WriteLine("num={0}", num);
            ShowDouble(ref num);
            Console.WriteLine("num={0}", num);

 

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

namespace KYExpress.Common
{
    public class ColumnAttributeTypeMapper<T> : FallbackTypeMapper
    {
        public ColumnAttributeTypeMapper()
            : base(new SqlMapper.ITypeMap[]
                {
                    new CustomPropertyTypeMap(
                       typeof(T),
                       (type, columnName) =>
                           type.GetProperties().FirstOrDefault(prop =>
                               prop.GetCustomAttributes(false)
                                   .OfType<ColumnAttribute>()
                                   .Any(attr => attr.Name == columnName)
                               )
                       ),
                    new DefaultTypeMap(typeof(T))
                })
        {
        }
    }

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
    public class ColumnAttribute : Attribute
    {
        public string Name { get; set; }
    }

    public class FallbackTypeMapper : SqlMapper.ITypeMap
    {
        private readonly IEnumerable<SqlMapper.ITypeMap> _mappers;

        public FallbackTypeMapper(IEnumerable<SqlMapper.ITypeMap> mappers)
        {
            _mappers = mappers;
        }


        public ConstructorInfo FindConstructor(string[] names, Type[] types)
        {
            foreach (var mapper in _mappers)
            {
                try
                {
                    ConstructorInfo result = mapper.FindConstructor(names, types);
                    if (result != null)
                    {
                        return result;
                    }
                }
                catch (NotImplementedException)
                {
                }
            }
            return null;
        }

        public SqlMapper.IMemberMap GetConstructorParameter(ConstructorInfo constructor, string columnName)
        {
            foreach (var mapper in _mappers)
            {
                try
                {
                    var result = mapper.GetConstructorParameter(constructor, columnName);
                    if (result != null)
                    {
                        return result;
                    }
                }
                catch (NotImplementedException)
                {
                }
            }
            return null;
        }

        public SqlMapper.IMemberMap GetMember(string columnName)
        {
            foreach (var mapper in _mappers)
            {
                try
                {
                    var result = mapper.GetMember(columnName);
                    if (result != null)
                    {
                        return result;
                    }
                }
                catch (NotImplementedException)
                {
                }
            }
            return null;
        }


        public ConstructorInfo FindExplicitConstructor()
        {
            return _mappers
                .Select(mapper => mapper.FindExplicitConstructor())
                .FirstOrDefault(result => result != null);
        }
    }

}

单黄金年代性:只可以从四个基类中持续,不可能同一时候继续八个基类继承中的访问修饰符base和this关键字基类的构造函数和析构函数不能够被接续的。但足以选取主要字base来三番六遍基类的构造函数。

出口参数(out卡塔 尔(英语:State of Qatar)

除去ref外,还是能钦点out关键字,钦命所给的参数时八个出口参数,out参数和ref参数都在函数定义和函数调用中作为参数的修饰符。事实上,它的实行格局与ref参数差不离完全相近,因为在函数执行完结后,该参数的值将回来给函数调用中央银行使的变量。可是,二者存在一些重要分裂:

1.把未赋值的变量用作ref参数是违法的,可是未赋值的变量可以用作out参数

2.在函数中使用out参数时,必需将其当做还没赋值。也正是说调用代码能够把已赋值的变量用作out参数,但在函数试行时该变量的值会遗失。

如以后有二个回到数组中最大值得马克斯(卡塔尔函数,获取数组中最大值得成分索引(这里假使要是有三个最大值,只回去第一个最大值索引卡塔 尔(阿拉伯语:قطر‎,增多out参数:

  static int Max(int[] intArray,out int maxIndex)
        {
            int maxVal = intArray[0];
            maxIndex = 0;
            for (int i = 1; i < intArray.Length; i++)
            {
                if(intArray[i]>maxVal)
                {
                    maxVal = intArray[i];
                    maxIndex = i;
                }
            }
            return maxVal;
        }

调用上面包车型客车代码:

 int[] myArray = { 1, 8, 3, 6, 2, 5, 9, 3, 0, 2 };
 int maxIndex;
 Console.WriteLine("the maxium value is {0}", Max(myArray, out maxIndex));
 Console.WriteLine("the index of the maxium value is{0}", maxIndex + 1);

垄断(monopoly卡塔尔国台出口的结果如下所示:

云顶娱乐yd2221 4

 

二、原理

利用示例方法如下:

C#中的base关键字表示基类,使用base关键字能够调用基类的构造函数、属性和艺术。

本文由云顶娱乐yd2221发布,转载请注明来源:世袭类实例云顶娱乐yd2221:,基于Dapper叁回封装