I am trying to use an object just for an expression but not sure if that is possible:
if ((new (Random)).Next(0,1))
{
}
This does not work, I would like to know whether it is even possible?
This will work... Note that what you wrote had multiple errors (logical and grammar)
if (new Random().Next(0,2) == 0)
And you aren't declaring an object, you are creating an object.
The syntax to create an object is new TypeName()
or new TypeName {}
. If the constructor has parameters, you have to use the syntax new TypeName(par1, par2)
.
Doing a new Random().Next(0, 1)
is totally useless... because it will generate a random number between 0 and 1 excluded, so 0 and 0, so 0 :-)
Other "logical" error: a Random
object should be reused, not created and used once and then discarded. This because a Random
object "represents" a sequence of random numbers (based on the seed). If you create multiple Random
objects in a short time, they'll often use the same seed, and generate the same sequence. new Random().Next() == new Random().Next()
99 times out of 100.
You can even do more awful things (note the bold)...
Random rnd;
if ((rnd = new Random()).Next(0, 2) == 0)
This because the assignment operator =
"returns" the value assigned, so you are assigning new Random()
to rnd
, and then you are taking the assigned value and using it for the .Next
. Note the additional brackets around the assignment.
If your question is really Can I declare an object directly in the “if” expression? , then the answer is no! You can't declare a new variable inside the if
conditional expression... You can't do:
if ((Random rnd = new Random()).Next(0, 2) == 0)
The only keyword in C# that lets do it are the for cycle
:
for (Random rnd = new Random()...
and the using
(but this one is more limited, it can only work in IDisposable
)
You need to initialize it using ()
. It still doesn't return any boolean
result which is must for an if
condition.
Do it like this:
if (new Random().Next(0,2) == 1)
This is not possible because
您需要将其更改为if(new Random()。next(0,2)== 0)并且应该没有任何问题...
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.