c# - 分配和方法调用顺序

标签 c# c#-4.0 call normalize

我写了这样一个属性(代表我的 XNA 游戏对象的方向):

public Vector2 Direction
{
    get { return direction; }
    protected set
    {
        (direction = value).Normalize(); // ***
        angle = MathHelper.WrapAngle((float)Math.Atan(direction.X / direction.Y));
    }
}

set 设置两个等效字段,分别以角度和标准化向量表示对象的方向。

开始游戏失败,因为***标记的行失败。它不会标准化矢量。
我将此行更改为:

direction = value;
direction.Normalize();

而且效果很好...为什么?
我假设在 *** 标记的行中,第一个操作是分配,然后标准化方向。但这不是真的。

___ ___ ____
Normalize()Vector2 类的方法。

//
// Summary:
//     Turns the current vector into a unit vector. The result is a vector one unit
//     in length pointing in the same direction as the original vector.
public void Normalize();

最佳答案

我假设 Vector2 是一个结构体或值类型,这意味着它是按值传递而不是按引用传递。当您将值分配给方向时,您正在将方向设置为值的副本。此外,表达式 (direction = value) 返回的对象是一个副本,而不是direction 中的同一实例。您正在对一个从未存储在 setter block 之外的对象调用 Normalize。

出于同样的原因,您无法在从类的属性 getter 返回的结构上调用方法或设置属性。例如,如果示例中的属性位于名为 Monkey 的类中,请注意:

Monkey m = new Monkey();
m.Direction = new Vector2(...);
m.Direction.X = 2; // This will not compile.
m.Direction.Normalize(); // This will not do what you expect.

关于c# - 分配和方法调用顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10461795/

相关文章:

javascript - ASP.NET Core 中无法正确读取 Cookie

c# - 如何将十进制数转换为时间,反之亦然

c# - EF 核心 : How to add the relationship to shadow property?

c# - 如何获取网页内容并将其保存到字符串变量中

c# - 接口(interface)可以在 C# 中有静态变量吗

javascript - 如何返回一个需要 2 个参数和 1 个参数的函数

swift - 在文本字段更改时调用函数

asp.net - 如何按需加载两个 ASP.NET UserControl?

java - 消费者没有将连接返回到我的数据库连接池

ios - 如果通话由医生收费,Apple 是否会对医生/患者视频通话应用收费?