简体   繁体   English

Vector3D.Normalize()有时不起作用

[英]Vector3D.Normalize() sometimes does not work

I use Vector3D.Normalize() in C# to compare different vectors. 我在C#中使用Vector3D.Normalize()比较不同的向量。 In some cases it did not work. 在某些情况下,它不起作用。 Therefore I made a simple sample just to show (not best coding). 因此,我做了一个简单的示例只是为了展示(不是最佳编码)。 How can I overcome this without using additional vectors like in Test2 ? 如何在不使用Test2等附加向量的情况下克服这一问题?

using System;
using System.Windows.Media.Media3D;

namespace Vecktor3D_Normalize_test
{
    class Program
    {
        static void Main(string[] args)
        {
            Vektor myVek = new Vektor();
            Vector3D myvector0 = new Vector3D(0.7, 0.5, 0.3);
            myVek.Test2(myvector0);
            Console.WriteLine("Test 2 " + myVek.myvector2);
            myVek.Test3(myvector0);
            Console.WriteLine("Test 3 " + myVek.myvector3);
            Console.WriteLine("Test 0 " + myvector0);
            myvector0.Normalize();
            Console.WriteLine("Test 1 " + myvector0);

            Console.ReadLine();
        }
    }
    class Vektor
    {
        public Vector3D myvector2 { get; set; }
        public Vector3D myvector3 { get; set; }
        public void Test2(Vector3D Input)
        {
            Vector3D myvector4 = Input;
            myvector4.Normalize(); // myvector4 is normalized !!!!!!
            myvector2 = myvector4;
        }
        public void Test3(Vector3D Input)
        {
            myvector3 = Input;
            myvector3.Normalize(); // myvector3 is not normalized !!!!!!!
        }
    }
}

Vector3D is a struct , so by default it is passed by value. Vector3Dstruct ,因此默认情况下按值传递。

This means myvector3.Normalize only normalizes a copy of myvector3 obtained from its get function, not myvector3 itself (or to be precise, the underlying hidden member variable which stores the value for the property myvector3 ). 这意味着myvector3.Normalize仅规范化从其get函数获得的myvector3副本 ,而不myvector3本身(或更确切地说,是存储属性myvector3的值的基础隐藏成员变量)。 Hence you must be careful when replacing member variables with properties. 因此,在用属性替换成员变量时必须小心。

You could instead call Normalize on Input , for the same reason: 出于相同的原因,您可以改为对Input调用Normalize

Input.Normalize();
myvector3 = Input;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM