簡體   English   中英

如何在 c# 中將兩個結構類型變量鏈接在一起?

[英]How do you link together two struct-type variables together in c#?

我的問題很簡單; 如何將兩個結構鏈接在一起,以便修改 c# 中的另一個? 由於結構的性質,這甚至可能嗎?

在代碼中,這就是我想要完成的:

Vector2 a = new Vector2(0.5f, 0.7f);
Vector2 b = a; // This line needs changing
b.X = 1.0f;
Debug.WriteLine(a.X); // should print 1.0f, but actually prints 0.5f.

對於上下文,我在 MonoGame 中制作游戲,需要將精靈位置鏈接在一起,這自然使用內置數據類型“Vector2”,它是一個結構。

結構是值類型,因此它們是按值復制的。 但是,您可以使用引用,如果您想通過引用參數或作為 class 成員的返回值來傳遞結構,這很方便。

例如

var a = new ValueTuple<string, int>("foo", 1);
ref var b = ref a;
        
b.Item2 = 2;
Console.WriteLine(a);

有關詳細信息,請參閱https://docs.microsoft.com/dotnet/csharp/programming-guide/classes-and-structs/ref-returns

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM