2
我想解決一個簡單的解析問題,我選擇使用枚舉來編碼選項列表。我怎樣才能一般地施放枚舉?
輸入數據是直接的ascii文本,分成具有唯一標頭和數據所在的非唯一標識符的塊。我能夠編寫相當一般的符號化方法,但不提供任何關於數據含義的上下文,並在返回後處理它。
用字符串做這件事沒有問題。我只是通過一個列表,我們走了。
我無法弄清楚枚舉枚舉的語法,我可以使用一些幫助。我也可能過於緊張,並且錯過了一個簡單的答案。
下面是與
private void parseToEnums(Enum returnEnum, string searchBlock, string startIDText,
string endIDText, string startText, string endText)
{
string ourSearchBlock = searchBlock;
int endIDidx = ourSearchBlock.IndexOf(endIDText);
while (ourSearchBlock.IndexOf(startText) != -1)
{
if (ourSearchBlock.Length == searchBlock.Length)
{
// first pass, trim off the region where the start text isn't valid
ourSearchBlock = ourSearchBlock.Remove(endIDidx, ourSearchBlock.Length - endIDidx);
// first pass, use the startIDtext to create a valid search zone
// BROKEN CODE HERE
// Neither GetType() nor typeof seem to do the right thing
// I have tried several varieties and have tried casting the LHS in the
// same sort of way
// pluckText returns a string that is guaranteed to match an enum name
returnEnum = (returnEnum.GetType()) System.Enum.Parse(typeof(returnEnum), pluckText(ourSearchBlock, startIDText, startText, endText), false);
ourSearchBlock = ourSearchBlock.Remove(0, ourSearchBlock.IndexOf(startIDText) + startIDText.Length);
}
else
{
// this would be similar to the above after it's working
// and is for the case where the string has multiple matches
// within the enum, ie "red white"
//returnList.Add(pluckText(ourSearchBlock, "", startText, endText));
}
ourSearchBlock = ourSearchBlock.Remove(0, ourSearchBlock.IndexOf(startText) + startText.Length);
}
return;
}
例子中,我有一個很難的代碼我在做什麼
private enum Colors { red, white, green };
private enum Suits { spades, clubs, hearts, diamonds };
// ... open files, read data, etc
// so I pass in the enum that I want my result in and some text identifiers
parseToEnum (Colors, searchBlock, "startColorBlock", "endColorBlock", "id=");
parseToEnum (Suits, searchBlock, "startCardSuitsBlock", "endCardSuitsBlock", "<id=");
// ...
這樣的想法是使用相同的結構(因爲輸入是相同),但對輸出使用不同的枚舉。
我知道我需要添加一些try/catch包裝和一般錯誤檢測到這個代碼之前太多。
隨意忽略搜索:-)如果我沒有包括它,有人會說我沒有提供足夠的細節。我很喜歡這個,並且會給它一個旋轉。 – Stephen 2012-02-28 21:52:48
我也喜歡我可以寫顏色和= Par ...;用這種方法。 – Stephen 2012-02-28 21:54:05
你寫這個,但它可能不會按你想要的方式工作。如果你想有一個'enum',它可以同時代表多個值,你必須將這些值設置爲不重疊的二進制值(例如1,2,4,8 ......),並使用'|'來組合他們。 – svick 2012-02-28 22:04:05