如何创建字母数字自动增量 [英] How to create Alphanumeric Auto Increment

查看:44
本文介绍了如何创建字母数字自动增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以指导我,或者至少给我教程链接,我想创建一个字母数字自动增量ID/代码,其格式为123-A00000010-A12,其中123和A12是常数,而A00000010是自动增量.

Can someone guide me or at least give me tutorial links I wanted to create an alphanumeric auto increment ID/Code with the following format 123-A00000010-A12 the 123 and A12 is constant and the A00000010 is auto increment.

推荐答案

对于一个简单的任务来说可能有些矫kill过正,但我​​想做点运动:

Probably some overkill for a simple task, but I felt like doing an exercise:

ID类

public class AlphaNumericID
{
    private string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public int Alpha { get; protected set;}
    public int Numeric { get; protected set; }

    public int NumericLenght { get; protected set; }

    public string KeyFront { get; protected set; }
    public string KeyEnd { get; protected set; }

    public AlphaNumericID(string keyFront, string keyEnd, int numericLength)
    {
        Alpha = 0;
        Numeric = 1;

        KeyFront = keyFront;
        KeyEnd = keyEnd;

        NumericLenght = numericLength;
    }

    public void Increment()
    {
        Numeric++;

        if (Numeric == Math.Pow(10, NumericLenght))
        {
            Alpha++;
            Numeric = 1;

            if (Alpha == chars.Length)
                throw new Exception("Overflow!");
        }
    }

    public override string ToString()
    {
        return String.Format("{0}-{1}{2}-{3}", KeyFront, chars[Alpha], Numeric.ToString().PadLeft(NumericLenght, '0'), KeyEnd);
    }
}

您可以这样使用:

  • 声明

var id = new AlphaNumericID("123", "A12", 8); //Will create 123-A00000001-A12

(尽管如果您知道数据库永远不会变得如此高,您可能需要考虑使用更短的ID)

(Although if you know your database will never go so high you may want to consider using a shorter id)

增量

id.Increment();

  • 输出

  • Output

    id.ToString();
    

  • 这种封装的好处是,您可以轻松扩展和更改其内部实现,尽管对于您的特定需求而言,它可能太大了.

    The benefit of this encapsulation is that you can extend and change its inner implementation easily, although it might be way too large for your particular needs.

    这篇关于如何创建字母数字自动增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆