Unique identifier
I want to generate a unique ide开发者_如何学JAVAntifier in .NET with the following format:
xxxxx-xxxxx
where x is a number {0-9};
I want to generate a unique identifier in .NET with the following format: xxxxx-xxxxx where x is a number {0-9}
Sure, no problem. We don't need to write a program for that. We'll just do it by hand.
00000-00000 is a unique identifier that has that format. Done.
Oh, you want more than one? Well, you probably should have said that in the problem statement. :)
There are ten billion strings in that language and it is trivial to generate them all in order. So, generate 00000-00000 for your first unique identifier. Then 00000-00001 for your second unique identifier. Then 00000-00002 for your third unique identifier. And so on. You will be able to generate ten billion unique identifiers in this way; all you have to do is keep track of which one was the highest previously generated.
Well, it's not going to be anywhere near as unique as a real Guid, but you could just use Random to generate each digit. Be sure to use a private static Random object to avoid getting the same random sequence:
private static m_random as new System.Random();
public string MySpecialID()
{
return string.Format("{0}{1}{2}{3}{4}-{5}{6}{7}{8}{9}",
m_random.Next(0, 10),
m_random.Next(0, 10),
m_random.Next(0, 10),
m_random.Next(0, 10),
m_random.Next(0, 10),
m_random.Next(0, 10),
m_random.Next(0, 10),
m_random.Next(0, 10),
m_random.Next(0, 10),
m_random.Next(0, 10));
}
精彩评论