[英]Can I declare an object directly in the “if” expression?
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 {}
. 创建对象的语法是new TypeName()
或new TypeName {}
。 If the constructor has parameters, you have to use the syntax new TypeName(par1, par2)
. 如果构造函数具有参数,则必须使用语法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 :-) 进行一个new Random().Next(0, 1)
完全没有用处...因为它将生成一个介于0和1之间的随机数,所以排除了0和0,所以0 :-)
Other "logical" error: a Random
object should be reused, not created and used once and then discarded. 其他“逻辑”错误:应该重用Random
对象,而不是一次创建和使用它,然后将其丢弃。 This because a Random
object "represents" a sequence of random numbers (based on the seed). 这是因为Random
对象“代表”一个随机数序列(基于种子)。 If you create multiple Random
objects in a short time, they'll often use the same seed, and generate the same sequence. 如果您在短时间内创建多个Random
对象,则它们通常会使用相同的种子,并生成相同的序列。 new Random().Next() == new Random().Next()
99 times out of 100. new Random().Next() == new Random().Next()
100的99次。
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
. 这是因为赋值运算符=
“返回”分配的值,因此您要向rnd
分配new Random()
,然后将分配的值用于.Next
。 Note the additional brackets around the assignment. 注意作业周围的其他括号。
If your question is really Can I declare an object directly in the “if” expression? 如果您的问题确实是, 我可以直接在“ if”表达式中声明一个对象吗? , then the answer is no! ,那么答案是否定的! You can't declare a new variable inside the if
conditional expression... You can't do: 您不能在if
条件表达式中声明新变量...您不能这样做:
if ((Random rnd = new Random()).Next(0, 2) == 0)
The only keyword in C# that lets do it are the for cycle
: C#中唯一允许这样做的关键字是for cycle
:
for (Random rnd = new Random()...
and the using
(but this one is more limited, it can only work in IDisposable
) 和using
(但这一方法比较有限,只能在IDisposable
)
You need to initialize it using ()
. 您需要使用()
对其进行初始化。 It still doesn't return any boolean
result which is must for an if
condition. 它仍然不返回任何if
条件必须的boolean
结果。
Do it like this: 像这样做:
if (new Random().Next(0,2) == 1)
This is not possible because 这是不可能的,因为
您需要将其更改为if(new Random()。next(0,2)== 0)并且应该没有任何问题...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.