用参数传递构造函数?

时间:2014-11-15 20:12:13

标签: c# constructor xna arguments

您好我在使用我的类的参数传递构造函数时遇到问题。那是:

    // Non-static variables exist once for each instance of the class
    Vector2 position;

    public Vector2 Position { get { return position; } }
    public myClass(Vector2 position)
    {
        this.position = position;
    }

我试图像这样(Game1类)实例化它:

myClass myClassInstance;

protected override void Initialize()
{
    // TODO: Add your initialization logic here.
    myClassInstance = new myClass(Position);
    base.Initialize();
}

但我在Initialize()

时收到此错误
Error   1   The name 'Position' does not exist in the current context

1 个答案:

答案 0 :(得分:2)

您的Initialize方法没有任何类型的"位置"在范围内声明的变量。例如,您可能会这样做:

myClass myClassInstance;

protected override void Initialize()
{
    // variables defined in a function are typically lower-case in C#
    Vector2 position = new Vector2(0,0);

    // I changed "Position" to "position" to match the variable
    myClassInstance = new myClass(position);
    base.Initialize();
}

然而,这里更大的问题可能是你需要花费一点时间来继续加速你的C#,因为这可能是你遇到的许多问题中的第一个,如果语法没有& #39;对你有意义。这是一个很棒的视频系列:

https://www.youtube.com/playlist?list=PLMUNVW3VsMWUB9mPN10vU6jvc_jbHvs1g