幾個替換字符串應該讓你開始的提示:
假設你的字符串處理函數被稱爲ProcessStrings。
1)將Constants.cs包含到與ProcessStrings函數相同的項目中,因此它將與重構代碼一起編譯。
2)反映了你的常量類構建語言字符串常量名的解釋,是這樣的:
Dictionary<String, String> constantList = new Dictionary<String, String>();
FieldInfo[] fields = typeof(Constants).GetFields(BindingFlags.Static | BindingFlags.Public);
String constantValue;
foreach (FieldInfo field in fields)
{
if (field.FieldType == typeof(String))
{
constantValue = (string)field.GetValue(null);
constantList.Add(constantValue, field.Name);
}
}
3)constantList現在應該包含常量名的完整列表,由字符串索引他們代表。
4)從文件中抓取所有行(使用File.ReadAllLines)。
5)現在遍歷這些行。像下面這樣的東西應該允許你忽略你不應該處理的行。
//check if the line is a comment or xml comment
if (Regex.IsMatch(lines[idx], @"^\s*//"))
continue;
//check if the entry is an attribute
if (Regex.IsMatch(lines[idx], @"^\s*\["))
continue;
//check if the line is part of a block comment (assuming a * at the start of the line)
if (Regex.IsMatch(lines[idx], @"^\s*(/\*+|\*+)"))
continue;
//check if the line has been marked as ignored
//(this is something handy I use to mark a string to be ignored for any reason, just put //IgnoreString at the end of the line)
if (Regex.IsMatch(lines[idx], @"//\s*IgnoreString\s*$"))
continue;
6)現在,匹配線上的任何引用字符串,然後通過每個匹配並檢查它的幾個條件。如果需要,您可以刪除其中一些條件。
MatchCollection mC = Regex.Matches(lines[idx], "@?\"([^\"]+)\"");
foreach (Match m in mC)
{
if (
// Detect format insertion markers that are on their own and ignore them,
!Regex.IsMatch(m.Value, @"""\s*\{\d(:\d+)?\}\s*""") &&
//or check for strings of single character length that are not proper characters (-, /, etc)
!Regex.IsMatch(m.Value, @"""\s*\\?[^\w]\s*""") &&
//check for digit only strings, allowing for decimal places and an optional percentage or multiplier indicator
!Regex.IsMatch(m.Value, @"""[\d.]+[%|x]?""") &&
//check for array indexers
!(m.Index <= lines[idx].Length && lines[idx][m.Index - 1] == '[' && lines[idx][m.Index + m.Length] == ']') &&
)
{
String toCheck = m.Groups[1].Value;
//look up the string we found in our list of constants
if (constantList.ContainsKey(toCheck))
{
String replaceString;
replaceString = "Constants." + constants[toCheck];
//replace the line in the file
lines[idx] = lines[idx].Replace("\"" + m.Groups[1].Value + "\"", replaceString);
}
else
{
//See Point 8....
}
}
7)現在加入備份行數組,並將其寫回文件。這應該會讓你獲得最大的成功。
8)爲了讓它產生字符串的常量,你還沒有一個條目,在else塊中查找字符串, 爲字符串中的常量生成一個名字(我剛剛刪除了所有特殊的字符和空格,並將其限制爲10個字)。然後使用該名稱和原始字符串(來自點6中的toCheck
變量)進行常量聲明並將其插入到Constants.cs中。 然後,當你再次運行該函數時,將使用這些新的常量。
你不能創建資源文件嗎? – Jonathan 2011-05-06 05:26:24
不,我必須從另一個cs文件加載它。很少開發人員而不是設計師:) – Harish 2011-05-06 05:30:02