다른 답변에도이를 수행하는 방법이 나와 있지만. 나는 그들에게 조언 할 것이고, 나는 올바른 도구를 사용할 것이다.
당신이 원하는 무엇을, 개념적, 문자열, 성적 (정수)를 변환하는 사전, 그래서 나는 그 길 갈 것 : 당신이 특정 경우
// We are going to use integer keys, with string values
var stringGrades = new Dictionary<int, string>()
{
{1, "good"}, // 1 is the Key, "good" is the Value
{2, "decent"},
{3, "bad"}
};
int integerGrade;
string textGrade;
// try to convert the textbox text to an integer
if(!Int32.TryParse(txtb_note.Text, out integerGrade)
// if successful, try to find the resulting integer
// (now in "integerGrade") among the keys of the dictionary
|| !stringGrades.TryGetValue(integerGrade, out textGrade))
// Any of the above conditions weren't successful, so it's invalid
lbl_ergebnis.Text = "Invalid value";
else
// It worked, so now we have our string value in the variable "textGrade"
// obtained by the "out textGrade" parameter on TryGetValue
lbl_ergebnis.Text = textGrade;
을 텍스트 상자에서 문자열로 원래의 등급을 사용하여, 그래서 그 경로를 이동하는 것은 당신이 선호하는 경우 :
// This time, we directly use string as keys
var stringGrades = new Dictionary<string, string>()
{
{"1", "good"},
{"2", "decent"},
{"3", "bad"}
};
string textGrade;
// Try to get the value in the dictionary for the key matching the text
// on your textbox, no need to convert to integer
if(!stringGrades.TryGetValue(txtb_note.Text, out textGrade))
lbl_ergebnis.Text = "Invalid value";
else
lbl_ergebnis.Text = textGrade;
TryGetValue
이후와 out
매개 변수를 혼동 할 수 있습니다, 여기 쉬울 수 있습니다 그것을 할 수있는 또 다른 방법은,이다
: 당신이 싶어 루프 루프처럼, 한 줄의 코드로 번역 될 수 있다면
// If our dictionary doesn't contain the key we are looking for,
// the input is invalid
if(!stringGrades.ContainsKey(txtb_note.Text))
lbl_ergebnis.Text = "Invalid value";
else
// it contains the key, so let's show its value:
lbl_ergebnis.Text = stringGrades[txtb_note.Text];
어느 : 당신이 프로그래밍에 새로운 경우 읽기 (우리는 위와 같은 <string, string>
사전을 사용합니다)
lbl_ergebnis.Text = stringGrades.ContainsKey(txtb_note.Text) ?
stringGrades[txtb_note.Text] : "Invalid value";
다른 방법
(
switch
또는
if-else
사용) 작업 (내가 말했듯이 그건 그냥 "루프를 반복"이야,이 마지막 코드에 의해 혼란스러워하지 않음)가 아니라 있습니다 오른쪽 t ool. 개념적으로 생각하고 원하는 것은 값을 다른 값으로 변환하는 것입니다. 사전이며 .NET (
Dictionary<T,T2>
클래스)에 해당 도구가 있습니다.
향후 다른 성적이 필요한 경우, 사전에 추가하면 문자열을 변환하는 코드가 계속 작동합니다. 또한 사전을 코드에 저장할 필요가 없습니다. 텍스트 파일, 웹 서비스, 데이터베이스 등에서 검색 할 수 있으며 응용 프로그램을 다시 컴파일하지 않고도 사용할 수 있습니다.
* numbers *를 처리하려는 경우 * 문자열 *이있는 순간에는 문자열을 구문 분석해야합니다. 'Int32.TryParse'는 아마도 좋은 출발일 것입니다 ... –
btw : 열거자인 – jean
을 또 다른 변형으로 볼 수 있습니다 : [switch] (https://msdn.microsoft.com/en-us/library/06tc147t) .aspx) like'switch (txtb_note.Text) {case "1": ... break; case "2": ... 휴식; ...; ' – Grundy