我已经使用C ++一段时间了,几周前我就选择了C#。在编写初始化程序时,我发现我不知道使用::运算符的方法。
在C ++中,它看起来像:
class something{
bool a;
void doSg();
}
void doSg(){
something::a = true;
}
int main()
{
something mySg;
mySg.doSg();
}
因此,我尝试在C#中重新创建void doSg()
函数:一种修改该类对象的数据的方法。
在以下代码中:
class something
{
bool a;
public void func()
{
this.a = true;
}
}
class source
{
something mySg;
mySg.func();
}
this.a = true
有效,或者我应该制作:
class something
{
bool a;
public myclass func(myclass item)
{
item.a = true;
return item;
}
}
class source
{
something mySg;
mySg = func(mySg);
}
或者有更好的解决方案吗?
答案 0 :(得分:2)
var这里是一个关键字,所以它可能不会像你使用它一样工作。你可以这样做:
class something {
bool myBool;
public void func()
{
this.myBool= true;
myBool= true; //or you can just leave this "this" off
}
}
当调用 something.func()时,它会将myBool设置为true。
"这"只是引用类(或结构)本身,不需要经常使用。如果有像这样的重复名称,你只需要它......
class something {
bool myBool;
public void func(bool myBool)
{
myBool= myBool; //would not do anything
this.myBool= myBool; //force class myBool
}
}
至于返回,你需要为你列出的第二个例子,但需要更改或删除var。
class something
{
public Myclass func(myclass item)
{
Myclass item = new myClass(); // first create a class
return item; //since myclass in in the header, we need to return a myclass
}
}
我将myClass更新为MyClass,因为类应该以captial开头,但这不是必需的。我希望这会有所帮助。当涉及到所有细节时,C#与C ++不同。