[英]C# pointer reference
有沒有辦法在 c# 中創建 c++ 樣式指針? 當我不知道它是哪個 int 時,我需要它在幾個地方設置一個 int。
就像在 c++ 中一樣,我會這樣做:
int *i;
if(cond0) i = &someint;
if(cond1) i = &otherint;
if(cond2) i = &thirdint;
if(cond3) *i = someval;
if(cond4) *i = otherval;
if(cond5) *i = thirdval;
如果我以 c# 樣式執行此操作,我將需要 9 個 if,並且我的程序有更多條件,因此它不可行。
我想做出某種價值,比如:
int val;
if(cond3) val = someval;
if(cond4) val = otherval;
if(cond5) val = thirdval;
if(cond0) someint = val;
if(cond1) otherint = val;
if(cond2) thirdint = val;
但這是不可能的,因為 cond3、4 和 5 分散在程序中。
是的,有一種稱為 IntPtr 的類型,我用於 Windows 句柄。
這是 C# 指針的示例,說明了它們的聲明以及如何將它們包裝在不安全的塊中
另請參閱C# 編程指南 - 指針類型
我不確定您是否在問題中提供了足夠的信息來給出正確答案,但一種可能的解決方案是使用 ref 參數設置 function 中的值。
class Program
{
static void Main(string[] args)
{
var i = 1;
var someint = 2;
var otherint = 3;
var thirdint = 4;
Console.WriteLine("i: {0}\nsomeint: {1}\notherint: {2}\nthirdint: {3}", i, someint, otherint, thirdint);
SetInts(true, false, false, false, false, false, ref i, ref someint, ref otherint, ref thirdint);
Console.WriteLine("i: {0}\nsomeint: {1}\notherint: {2}\nthirdint: {3}", i, someint, otherint, thirdint);
Console.ReadKey();
}
static void SetInts(bool cond0, bool cond1, bool cond2, bool cond3, bool cond4, bool cond5, ref int i, ref int someint, ref int otherint, ref int thirdint)
{
if (cond0) i = someint;
if (cond1) i = otherint;
if (cond2) i = thirdint;
if (cond3) i = someint;
if (cond4) i = otherint;
if (cond5) i = thirdint;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.