开发者

Problem while invoking a Function from a Class

I have a class that name Cleint in that i have a function ,i want to make a three instantiate from Cleint with diffrent result of a Function but the results are same here is my code:

Programm.cs:

class Program
    {
        static void Main(string[] args)
        {
            Cle开发者_Python百科int B = new Cleint();
            Cleint k = new Cleint();
            Cleint S = new Cleint();
            Console.WriteLine(B.GenerateAddress());
            Console.WriteLine(k.GenerateAddress());
            Console.WriteLine(S.GenerateAddress());
            Console.ReadLine();


        }
    }

and Cleint.cs:

class Cleint
    {
        public string GenerateAddress()
        {
            var parts = new List<string>();
            Random random = new Random();
            for (int i = 0; i < 4; i++)
            {
                int newPart = random.Next(0, 255);
                parts.Add(newPart.ToString());
            }
            string address = string.Join(".", parts);
            p;
            return address;
        }
    }

thank's for your help


Random is not really random - it is pseudo random and the default constructor uses the current time as the seed for the sequence.

When called in quick succession, this time will be the same and the sequence be the same.

You can use a static field to ensure you are using the same Random instance if you are only ever going to have one thread (as Random is not thread safe):

class Cleint
{
    private static Random random = new Random();

    public string GenerateAddress()
    {
        var parts = new List<string>();
        for (int i = 0; i < 4; i++)
        {
            int newPart = random.Next(0, 255);
            parts.Add(newPart.ToString());
        }
        string address = string.Join(".", parts);

        return address;
    }
}


The problem is how you're using random number generation - you're creating a new instance of Random in each case.

See my article on random numbers for details, but basically you should use the same instance of Random for all the calls.

Assuming your classes aren't designed to be multithreaded, you could change it to either have a Random field in Client, or have a Random parameter in GenerateAddress. Either way, you'd create a single instance in Main and pass a reference to that same instance for all three cases.


When you create a new Random object, it uses the current time on your PC as the seed for it's generator. If you create many Random objects in a fast succession, they'll generate the same "random" numbers.

Try creating a single Random object and generating from that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜