更新时间:2023-12-02 15:57:34
我看到的唯一重要区别是static
on the original - 在C#中没有equivelant。
在C和C ++中,静态局部变量的作用域是函数,但是值不是基于堆栈的 - 它在方法的执行中保留因此,如果你这次更改它,下次调用该函数时它将具有新值。 C#没有这样的东西,所以你的变量必须在类级别声明,有或没有static
关键字,具体取决于方法声明。
但一般来说,将C或C ++代码直接转换为C#是一个坏主意:你不会得到好的C#。重写它以使用C#功能和.NET类通常是一个更好的主意。
GetTickCount()
调用用于获取存储在静态变量中的随机起始值(仅在程序启动时调用一次)。转换为short
会将值限制为16位(忽略更高位)。
您可以创建一个静态类,并使用C#Random类进行类似的行为:public class MyClass
{
static int 一世;
static MyClass()
{
i = Environment.TickCount()& 0xFFFF的;
// 或
/ / 随机随机=新的随机();
// i = random.Next(0,0xffff);
}
void DoIt()
{
if (〜我& 2 )
{
i + = 3U;
}
else
{
i + = 5U;
}
}
};
这应该可以,但你省略了静态限定符。这导致C ++代码是代码只执行一次,我称之为气味或错误。我不知道你的代码,但我认为静态是错误的。
顺便说一句:在C ++代码中,你将滴答计数限制为无符号短,所以松散了较高位,但你不需要它们用于if。
static unsigned int i = (unsigned short)((signed short)GetTickCount()); if( ~i & 2 ) { i+=3U; } else { i+=5U; }
this is some c++ code which i want to convert it to c# plz help
What I have tried:
uint i = GetTickCount(); if( ~i & 2 ) { i+=3U; } else { i+=5U; }
The only significant difference I see is thestatic
on the original - which has no equivelant in C#.
In C and C++ a static local variable is scoped to the function, but the value is not stack based - it is preserved across executions of the method so if you change it this time it will have the new value next time the function is called. C# does not have anything like that, so your variable would have to be declared at class level, with or without thestatic
keyword depending on the method declaration.
But generally, converting C or C++ code directly to C# is a bad idea: you do not end up with "good C#". Rewriting it to use C# features and .NET classes is normally a much better idea.
TheGetTickCount()
call is used to get a random start value stored in a static variable (it is only called once at program start). The casting toshort
will limit the value to 16 bits (ignore the higher bits).
You can create a static class and also use the C# Random class for similar behaviour :public class MyClass { static int i; static MyClass() { i = Environment.TickCount() & 0xffff; // Or //Random random = new Random(); //i = random.Next(0, 0xffff); } void DoIt() { if( ~i & 2 ) { i+=3U; } else { i+=5U; } } };
That should work but you left out the static qualifier. This results in the C++ code is that the code is only executed once, what I would call a smell or a bug. I dont know your code, but I think the static is wrong.
BTW: In the C++ code you cap the tick count to a unsigned short and so loose the higher bits, but you dont need them for your if.