2012-12-01 61 views
2

我有一個靜態函數:訪問從靜態函數

static string GenRan() 
{ 
    List<string> s = new List<string> {"a", "b"}; 
    int r = Rand(); 
    string a = null; 

    if (r == 1) 
    { 
     a += s[0]; 
     s.RemoveAt(0); 
    } 
    if (r == 2) 
    { 
     a += s[1]; 
     s.RemoveAt(1); 
    } 
    return a; 
} 

但每次我打電話過程中的功能,都會被重置,所以我想從靜態函數外部訪問列表。

有沒有辦法?

我想:

static void Main(string[] args) 
{ 
    List<string> s = new List<string> {"a", "b"}; 
    string out = GenRan(s); 
} 

static string GenRan(List<string> dict) 
{ 

    int r = Rand(); 
    string a = null; 

    if (r == 1) 
    { 
     a += s[0]; 
     s.RemoveAt(0); 
    } 
    if (r == 2) 
    { 
     a += s[1]; 
     s.RemoveAt(1); 
    } 
    return a; 
} 

但後來我得到一個指數是超出範圍的錯誤(不知道爲什麼)。

任何人都可以幫忙嗎?

回答

9

你需要將它添加到類爲static field變量:

private static List<string> s = new List<string> { "a", "b" }; 

static string GenRan() 
{ 
    int r = Rand(); 
    string a = null; 

    if (r == 1) 
    { 
     a += s[0]; 
     s.RemoveAt(0); 
    } 
    if (r == 2) 
    { 
     a += s[1]; 
     s.RemoveAt(1); 
    } 
    return a; 
} 
1

但每次我打電話過程中的功能,都會被重置,所以我想從外部訪問的列表靜態功能。

這不是真的清楚你的意思,但如果你的意思是你想要的清單是調用之間持久的,你需要將其聲明爲靜態變量,方法外:

private static readonly List<string> s = new List<string> {"a", "b"}; 

現在你可以從任何方法訪問列表,它基本上是類的一部分。然而,這種方法帶有很多需要注意的地方

  • List<T>是不是線程安全的,並且通常是靜態的方法應該是線程安全的。如果你剛剛接觸C#而不使用多線程,那麼你現在可能會忽略它。
  • 您應該重新命名變量 - s並不表示該列表是什麼意思。
  • 一般來說,全局可變狀態是一個壞主意。它很難測試你的代碼,並推理它。同樣,如果你剛剛接觸C#並試驗,你可能不需要擔心這一點,但隨着你的繼續前進,你應該嘗試在對象中放置更多的可變狀態,而不僅僅是靜態變量。