Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

c# - 如何生成随机字母数字字符串?(How can I generate random alphanumeric strings?)

如何在C#中生成随机的8个字符的字母数字字符串?

  ask by KingNestor translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I heard LINQ is the new black, so here's my attempt using LINQ:

(我听说LINQ是新的黑色,所以这是我尝试使用LINQ:)

private static Random random = new Random();
public static string RandomString(int length)
{
    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    return new string(Enumerable.Repeat(chars, length)
      .Select(s => s[random.Next(s.Length)]).ToArray());
}

(Note: The use of the Random class makes this unsuitable for anything security related , such as creating passwords or tokens. Use the RNGCryptoServiceProvider class if you need a strong random number generator.)

((注意:使用Random类会使其不适用于任何与安全性相关的内容 ,例如创建密码或令牌。如果需要强大的随机数生成器,请使用RNGCryptoServiceProvider类。))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...