Generate random values in C#

后端 未结 9 1912
执笔经年
执笔经年 2020-12-01 06:15

How can I generate random Int64 and UInt64 values using the Random class in C#?

9条回答
  •  醉话见心
    2020-12-01 06:41

    Here you go, this uses the crytpo services (not the Random class), which is (theoretically) a better RNG then the Random class. You could easily make this an extension of Random or make your own Random class where the RNGCryptoServiceProvider is a class-level object.

    using System.Security.Cryptography;
    public static Int64 NextInt64()
    {
       var bytes = new byte[sizeof(Int64)];    
       RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();
       Gen.GetBytes(bytes);    
       return BitConverter.ToInt64(bytes , 0);        
    }
    

提交回复
热议问题