[英]Static extention methods in ASP.NET
我創建了一個簡單的擴展方法,可以將任何數字轉換為新的略短的文本。 它通過使用小於 10 的 10 個數值以及字母字符來實現這一點。
所以問題是,如果有同時訪問此方法的調用,代碼 char1 和 char2 是否會從一個用戶的會話被另一個用戶會話覆蓋
這是方法的代碼
public static string Translate35(this int value)
{ //O is just removed to avoid confusion between 0 and O
string[] Enc = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
int char1 = (value % Enc.Length);
int char2 = (value / Enc.Length) % Enc.Length;
int char3 = (int)(value / Math.Pow(Enc.Length, 2)) % Enc.Length;
int char4 = (int)(value / Math.Pow(Enc.Length, 3)) % Enc.Length;
int char5 = (int)(value / Math.Pow(Enc.Length, 4)) % Enc.Length;
return Enc[char5] + Enc[char4] + Enc[char3] + Enc[char2] + Enc[char1];
}
public static int Translate35(this string value)
{ //O is just removed to avoid confusion between 0 and O
string[] Enc = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
var indexEnc = Enc.Select((x, i) => new { charx = x, charindex = i }).ToDictionary(x => x.charx[0], x => x.charindex);
int char0 = (int)(indexEnc[value[0]] * Math.Pow(Enc.Length, 4));
int char1 = (int)(indexEnc[value[1]] * Math.Pow(Enc.Length, 3));
int char2 = (int)(indexEnc[value[2]] * Math.Pow(Enc.Length, 2));
int char3 = (int)(indexEnc[value[3]] * Math.Pow(Enc.Length, 1));
int char4 = indexEnc[value[4]];
return char4 + char3 + char2 + char1 + char0;
}
所以我試圖避免的是一個用戶的數據正在被這種方法操縱,並且隨着它到達
int char3 = (int)(value / Math.Pow(Enc.Length, 2)) % Enc.Length;
那么它的 char2 已經設置好了。
然后另一個用戶數據開始相同的過程並到達 char2 並執行
int char2 = (value / Enc.Length) % Enc.Length;
它是覆蓋第一個用戶變量還是保存,因為變量 char2 也不是靜態的。
這些方法沒有副作用。 除了接受輸入,在本地處理它並返回輸出之外,它們什么都不做。 所以大量並行調用沒有問題,因為沒有需要處理的共享資源。
如果您使用的是代碼注釋,則可以使用System.Diagnostics.Contracts.PureAttribute
或JetBrains.Annotations.PureAttribute
的[Pure]
屬性(如果您使用的是 Resharper)。
不過,它可能可以通過將靜態只讀數據移動到它自己的成員來優化一下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.