簡體   English   中英

在C#中的數組中存儲ushort的引用

[英]Store reference of an ushort in an array in c#

我想將ushort變量的引用存儲在ushort array ,以便當我更改ushort數組內的值時,變量的值也會更改。 這是我的示例代碼,它將清楚地說明我要實現的目標。

public void IndexSetter(List<int> indexVal,Rootobject objectVal)
{
    ushort[] refereneArray = new ushort[8] 
    {
        objectVal.index1, objectVal.index2, 
        objectVal.index3 , objectVal.index4,
        objectVal.index5, objectVal.index6, 
        objectVal.index7, objectVal.index8 
    };
    for(int j = 0; j< indexVal.Count;j++)
    {
        refereneArray[j] =(ushort) indexVal[j];
    }  
}

而不是像上面的代碼那樣存儲值,我需要存儲引用,以便indexVal列表中的更改反映在index1,index2等值中。

您可以使用不安全的代碼,使用如下指針數組來做到這一點:

static unsafe void IndexSetter(IList<ushort> indexVal, Rootobject objectVal) {
    fixed (ushort* r1 = &objectVal.index1)
    fixed (ushort* r2 = &objectVal.index2) {
        ushort*[] refereneArray = {r1, r2};
        for (int j = 0; j < indexVal.Count; j++) {
            *refereneArray[j] = (ushort) indexVal[j];
        }
    }
}

您是否應該在實際應用中真正做到這一點是另一回事。 很有可能有更好的方法來解決問題,但是您沒有告訴我們實際的問題是什么。

如果性能不是關鍵-您可以使用反射:

static void IndexSetter2(IList<ushort> indexVal, Rootobject objectVal) {
    int i = 0;
    foreach (var field in objectVal.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance)
                         .Where(c => c.Name.StartsWith("index") && c.FieldType == typeof(ushort))
                         .OrderBy(c => c.Name)) {
        field.SetValue(objectVal, indexVal[i]);
        i++;
    }
}

我建議不要使用名稱完全相同的8個索引(數字除外)。 給班上的每個成員一個名稱,描述其內容,但是index6index6解釋。

話雖如此,您可以做的是在類本身中具有一個索引數組:

class Rootobject
{
    public int[] Indexes { get; set; }
}

現在,您可以按以下方式訪問它們:

public void IndexSetter(List<int> indexVal, Rootobject objectVal)
{
    for(int i = 0; i < indexVal.Count; i++)
        objectVal.Indexes[index] = indexVal[i];
}

甚至更短:

objectVal.Indexes = indexVal.Cast<ushort>().ToArray();

暫無
暫無

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

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