using System.DateTime.Now.Ticks for seed value

naj*_*laa 1 c# seed

I have started a wireless sensor network simulation code but I don't understand the meaning of the seed and what is the return value of System.DateTime.Now.Ticks in the method below.

public void Reset(bool bNewSeed) {
    // this function resets the network so that a new simulation can be run - can either be reset with a new seed, or with the previous seed (for replay.)
    this.iProcessTime = 0;
    this.iPacketsDelivered = 0;
    foreach (WirelessSensor sensor in aSensors) {
        sensor.iResidualEnergy = sensor.iInitialEnergy;
        sensor.aPackets = new ArrayList();
        sensor.iSensorRadius = iSensorRadius;
        sensor.iSensorDelay = 0;
        foreach (WirelessSensorConnection connection in sensor.aConnections) {
            connection.iTransmitting = 0;
            connection.packet = null;
        }
    }
    aRadar = new ArrayList();
    if (bDirectedRouting == true)
        SetRoutingInformation();
    iLastUpdated = iUpdateDelay;
    if (bNewSeed == true)
        this.iSeed = (int) System.DateTime.Now.Ticks;
    r = new Random(iSeed);
}
Run Code Online (Sandbox Code Playgroud)

小智 5

DateTime.Now.Ticks returns a long which represents the number of ticks in that instance.

通过为Random您的实例提供种子值,可以指定用于计算伪随机数字序列起始值的数字。

因此,如果两个实例Random都具有相同的种子,则它们将生成相同的值,例如:

var randomOne = new Random(1);
var randomTwo = new Random(1);

var valOne = randomOne.Next(1, 1000);
var valTwo = randomTwo.Next(1, 1000);

valOne.Equals(valTwo); // True
Run Code Online (Sandbox Code Playgroud)

因此,为了制作一个随机实例,more random可以使用一个不太可能可预测的值,在您的情况下,DateTime例如

var random = new Random((int)DateTime.UtcNow.Ticks);
Run Code Online (Sandbox Code Playgroud)

或更好的方法是:

var random = new Random(Guid.NewGuid().GetHashCode());
Run Code Online (Sandbox Code Playgroud)

  • 为什么使用“Guid.NewGuid().GetHashCode()”是更好的方法?请激励。 (3认同)