Ch3*_*ire -8 c# reference this
假设我有一个C++代码:
class A {
int x = 20;
void Interact(A* Other) {
if (x % 2 == 0) { Other->x++; x /= 2; } //some advanced operation
}
public:
void MakeInteraction(A* Other) {
Interact(Other);
Other->Interact(this);
}
};
int main() {
A a, b;
a.MakeInteraction(&b);
}
Run Code Online (Sandbox Code Playgroud)
问题是,如果我想在C#中做类似的东西,我遇到了障碍 - 当然我不需要使用指针,但我不能使用this对象的引用:
class A
{
int x = 20;
void Interact(ref A Other)
{
if (x % 2 == 0) { Other.x++; x /= 2; }
}
public void MakeInteraction(ref A Other)
{
Interact(ref Other); //works
Other.Interact(ref this); //doesn't work
Other.Interact(this); //still doesn't work
A a = this;
Other.Interact(ref a);
this = a; //REALLY? THIS DOESN'T WORK TOO?!
}
}
Run Code Online (Sandbox Code Playgroud)
我很生气,因为我认为C#纠正了C++的缺陷,并留下了与最初的C++一样多的选项,减去了指针.现在看来,从C++转换到C#需要再次改变一种思维方式.
您不需要ref在参数声明中使用.对于像你这样的引用类型class A,声明为just的参数A other将导致C#传递对象的引用.
A other在C#中声明的参数与A* otherC++中的类似.
ref A other在C#中声明的参数与A** otherC++中的类似.
class A
{
int x = 20;
void Interact(A other)
{
if (x % 2 == 0) { other.x++; x /= 2; }
}
public void MakeInteraction(A other)
{
Interact(other);
other.Interact(this);
}
static void Main()
{
A a = new A();
A b = new A();
a.MakeInteraction(b);
}
}
Run Code Online (Sandbox Code Playgroud)