there is any way to match the method RAND(INT) of Visual Fox Pro and C #. Net

為{幸葍}努か 提交于 2019-12-01 20:46:46

Rand in .NET is not guaranteed to be the same between major revision numbers, so a Rand() with a seed of 1234 in 2.0 can be different than a Rand() in 4.0 with the exact same seed.

If you MUST match the old implientation you will need to find out how Visual Fox Pro did their Rand function. However, if you want same behavior, but not the same numbers you can hash the string just output that.

Random r = new Random (myTextBox.Text.GetHashCode()); 
return r.Next();

Now this is not cryptographically secure and is not guaranteed to generate the same number on different computers (it returns different numbers between 32 and 64 bit, and different versions based on the .Net run-time (This actually applies to both GetHashCode and Random itself!)), so don't store it a database!


If you need the same number out every time from the same string in no matter what computer it is on just use a RNGCryptoServiceProvider in the System.Security.Cryptography namespace.

//Returns the same number between 0 and 255 every time.
using(var myRng = new RNGCryptoServiceProvider(myTextBox.Text))
{
    var ret = new byte[1];
    myRng.GetBytes(ret);
    return ret[0];
}
Random r = new Random (intValue); 
return r.Next();

See the constructor for Random() :

Providing an identical seed value to different Random objects causes each instance to produce identical sequences of random numbers

In Visual FoxPro, you can generate the same sequence of random numbers repeatedly by calling RAND() once with a seed value, then omitting the seed on subsequent calls:

RAND(mySeed)
RAND()
RAND()

In C# you can do something similar by specifying a seed value as an argument to the Random constructor:

Random r = new Random (mySeed);  
r.Next(intValue); 
r.Next(intValue); 

I used the GetHashCode method on the string value to seed Random:

var s = "abcdefg";
var random = new Random(s.GetHashCode());
var hash = random.Next(10000, 99999));

Here are the results I got with a few test cases:

"abcdefg" => 43065
"abcdefg" => 43065
"defghij" => 62962
"qwerty"  => 72764
"defghij" => 62962
"qwerty"  => 72764
"abcdefg" => 43065
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!