0

I want to track a variable in my class that was created outside the scope. In C++ i'd just pass a pointer like this.

class Camera
{
    Player* player;
    Position pos;

    void setFollow(Player* pl) { pl = player; }
    void update() { pos = pl->getPos(); }
}

int Main()
{
    Camera* camera = new Camera();

    Player* player = new Player();

    camera->setFollow(player);
}

In C# I tried to pass by reference but it didnt seem to work.

public class Game1 : Microsoft.Xna.Framework.Game
{
    Camera cam = new Camera();
    Player player = new Player();

    cam.setFollow(ref player);  // <-- by reference
}

This is just a shortened version of my actual code.

Thanks for any help.

EDIT: Thanks to all for the information.

4

5 回答 5

3

在 C# 中,对象(类)变量是隐式指针。因此,如果您的类Camera有一个ptype 字段,那么在您的代码中进行Player设置cam.p = player将使两个引用都指向同一个实例。ref除非您通过引用传递值类型(int, float,structs等),否则通常不需要使用。

于 2012-04-23T12:19:22.780 回答
1

这里不需要使用ref关键字,因为在 C# 中对象总是通过引用传递。C# 中的ref关键字通常更像**C/C++ 中使用的指针指针 ( )

于 2012-04-23T12:18:17.367 回答
0

refC# 中的关键字有一个非常糟糕的名字。这并不意味着您通过引用传递!它应该被命名alias,因为这是描述语义的好词ref

// here I assign a reference(another bad name :) )
// you can also call it Garbage Collector Handler 
// of type Player with a new object
Player player = new Player(); 
// ref means that player is the same thing that parameter pl of setFollow
cam.setFollow(ref player); 

更多细节

于 2012-04-23T12:27:05.450 回答
0

Player 本身是一个引用类型,为什么要使用 ref. 您可以在此处阅读有关参考的更多信息 http://msdn.microsoft.com/en-us/library/14akc2c7.aspx

于 2012-04-23T12:17:49.663 回答
0

类总是通过引用传递,所以你不需要你想要做的 ref 位

简单地

cam.setFollow(player);
于 2012-04-23T12:18:07.000 回答