簡體   English   中英

以下C#代碼有什么作用?

[英]What does the following C# code do?

我在C#XNA圖形api中遇到了以下類,我不確定它是做什么的,或者它需要如此模糊。 (T被約束為父類中的結構)

    static class Ident
    {
        static object sync = new object();
        static volatile int index = 0;
        static int Index
        {
            get
            {
                lock (sync)
                    return index++;
            }
        }
        class Type<T>
        {
            public static int id = Index;
        }
        public static int TypeIndex<T>()
        {
            return Type<T>.id;
        }
    }

API僅在調用此靜態類時執行: int index = Ident.TypeIndex<T>();

它為每個不同類型T分配應用程序范圍(靜態)和線程安全(鎖定同步對象+易失性索引)唯一標識符。

例如:

Console.WriteLine(Ident.TypeIndex<int>()); // 0
Console.WriteLine(Ident.TypeIndex<string>()); // 1
Console.WriteLine(Ident.TypeIndex<long>()); // 2
Console.WriteLine(Ident.TypeIndex<int>()); // 0

Volatile用於確保當前線程不會緩存索引值,並且鎖定會阻止多個線程訪問它。

這將以線程安全的方式基於每個類型訪問的順序為每個類型創建唯一的整數標識符。

例如,如果你這樣做:

int myClassId = Ident.TypeIndex<MyClass>();
int mySecondClssId = Ident.TypeIndex<MySecondClass>();

您將得到2個“TypeIndex”數字(mySecondClassId至少比myClassId多1個,但由於線程可能更大)。 稍后,如果再次使用同一個類調用它,它將返回該類的相同TypeIndex。

例如,如果我運行它,使用:

Console.WriteLine(Ident.TypeIndex<Program>());
Console.WriteLine(Ident.TypeIndex<Test>());
Console.WriteLine(Ident.TypeIndex<Program>());
Console.WriteLine(Ident.TypeIndex<Test>());

它將打印:

0
1
0
1

但是,使用Interlocked.Increment可以更有效地完成此操作,這將完全避免鎖和同步對象的需要。 以下給出了完全相同的答案,不需要鎖定:

static class Ident
{
    static int index = -1;
    static int Index
    {
        get
        {

            return Interlocked.Increment(ref index);
        }
    }
    private static class Type<T>
    {
        public static int id = Index;
    }

    public static int TypeIndex<T>()
    {
        return Type<T>.id;
    }
} 

它返回調用Ident.TypeIndex的次數,可能是為每個對象分配一個唯一的編號。

由於他們使用泛型的方式,每種類型T應該有一個不同的數字序列。所以你可以有一個#1圓,一個#2圓和一個#1正方形。

暫無
暫無

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

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