可能很簡單或者之前問過,所以請原諒我再次問它。我正在嘗試學習 :)
如果我在 C# 中有一個字串型別變數,它將采用以下任何值:“Admin”“Editor”“Viewer”并且我還有 3 個與上述名稱相同的用戶表單,是否有任何方法可以簡單地使用變數值呼叫用戶表單而不是通過 switch 或 if/else 陳述句?像,你能有類似的東西:userform(x).show?x 是變數
會很感激的!
uj5u.com熱心網友回復:
- 對于“型別”,您應該使用列舉。
public enum UserType
{
Admin,
Editor,
Viewer,
}
- 如果您有需要字串表示的型別,您可以讓 C# 自動為您完成,或者撰寫您自己的:
UserType userType = UserType.Admin;
string s = userType.ToString(); // "Admin"
string s2 = UserType.Admin.ToString(); // "Admin" as well
public static string GetType(UserType type) => type switch
{
UserType.Admin => "Boss",
UserType.Editor => "Fact Checker",
UserType.Viewer => "Reader Bee",
_ => "",
};
要獲得這種型別的形式, aDictionary<UserType, Form>會很好:
Dictionary<UserType, Form> myForms = new(); // C#9 shorthand - "target typed new expression"
myForms.Add(UserType.Editor, editorForm);
myForms.Add(UserType.Admin, adminForm);
myForms.Add(UserType.Viewer, viewerForm);
editorForm.Text = UserType.Editor.ToString(); // use the built in string or...
editorForm.Text = GetType(UserType.Editor); // ... as defined above
如果要顯示特定表單,則可以執行以下操作:
UserType typeOfFormToShow = // ...
myForms[typeOfFormToShow].Show(); // Ensure this form exists in your dictionary, though.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/364122.html
標籤:C#
上一篇:檢查通用屬性的特定值
