简体   繁体   中英

C# Random 'new' Keyword

I started dabbling in Lua about a year ago and decided to learn C# instead when I recently discovered Unity!

All very exciting, but coming from an incredibly limited understanding of Lua, I'm really struggling with the concept of this:

// C# Random Number:    
Random r = new Random();
r.Next(5, 10)

As far as I can recall, in Lua I would simply do this:

-- Lua Random Number:
r =  math.random(5, 10)

My questions are:

  1. In C#, why do I have to create an instance of this Random class? Why can't I just grab a random value and assign it to 'r' from the Random.Next(5, 10) method with similar syntax to the Lua example above? (I ask this because I don't have to create a new instance of the Console class to call the WriteLine method... that is why I'm confused at this point).

  2. I have noticed that the IDE auto complete for Console shows: 'public static class' whereas for Random, it shows: 'public class'. If Console is 'static', is that the reason we don't need to create a 'new' instance?

I have read this: https://www.dotnetperls.com/static but the I'm missing some basic pieces of the puzzle, so still don't understand the concept fully.

I'm looking for help in understanding the concept, so please answer the questions with some examples (as if I'm a complete beginner).

This is due to the way in which the Random class works.

One of the reasons for a class to not be static is that it can have multiple instances with different states.

Random generates pseudo random numbers using a seed. If you use the same seed, the same numbers will be generated. Each Random instance has a seed as the state. If Random were a static class, only one seed can be used because you can't create instances with different seeds. When you create a Random object using the parameterless constructor, the system time is used as the seed.

Having Random as a non-static class allows client code to pass in the seeds they want to use, making the API more useful.

I have noticed that the IDE auto complete for Console shows: 'public static class' whereas for Random, it shows: 'public class'. If Console is 'static', is that the reason we don't need to create a 'new' instance?

No, you don't need to create a new instance of Console to use its methods. In fact, you can't even do new Console() at all! This is because there are not and should not be multiple consoles. There is only one console in the computer. It does not need to maintain multiple states, like the Random class with seeds and stuff.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM