生成主键,拒绝GUID

发布时间 2023-08-03 10:44:35作者: kueizheng

直接上代码

using System;
using System.Collections.Generic;
using System.Text;

namespace Library
{
    public class ParmaryKeyHelper
    {
        /// <summary>
        /// 获取主键
        /// </summary>
        /// <returns></returns>
        public static string GetPrimaryKey()
        {
            DateTime detNow = DateTime.Now;
            try
            {
                return string.Format("086028000{0}{1}", detNow.ToString("yyyyMMddHHmmss"), PrimaryKey.GetParamSequence());

            }
            catch (Exception ex)
            {
                throw new Exception("获取主键时发生错误:" + ex.Message);
            }
        }
    }


    class PrimaryKey
    {
        private static object objParam = new object();
        private static int ParamNo = 0;
        /// <summary>
        /// 获得系统参数序号
        /// </summary>
        /// <returns>序号值</returns>
        public static string GetParamSequence()
        {
            lock (objParam)
            {
                ParamNo++;
                if (ParamNo == 100000) ParamNo = 1;
                return ParamNo.ToString("00000");
            }
        }
    }
}
View Code

调用

ParmaryKeyHelper.GetPrimaryKey();