2010-10-21 75 views
2

存在我宣佈我的C#應用​​程序常數是這樣的:C#校驗值在不斷

public class Constant 
public struct profession 
{ 
    public const string STUDENT = "Student"; 
    public const string WORKING_PROFESSIONAL = "Working Professional"; 
    public const string OTHERS = "Others"; 
} 

public struct gender 
{ 
    public const string MALE = "M"; 
    public const string FEMALE = "F"; 
} 
} 

我的驗證功能:

public static bool isWithinAllowedSelection(string strValueToCheck, object constantClass) 
{ 

    //convert object to struct 

    //loop thru all const in struct 
      //if strValueToCheck matches any of the value in struct, return true 
    //end of loop 

    //return false 
} 

在運行時,我會想在用戶輸入的值傳遞和該結構檢查結構中是否存在該值。結構可以是職業和性別。我怎樣才能實現它?

例子:

if(!isWithinAllowedSelection(strInput,Constant.profession)){ 
    response.write("invalid profession"); 
} 

if(!isWithinAllowedSelection(strInput,Constant.gender)){ 
    response.write("invalid gender"); 
} 
+1

這聽起來像一個'enum'比結構更好的情況。 – RPM1984 2010-10-21 10:09:18

回答

4

你可能想使用enums,不是結構與常量。


枚舉給你很多的可能性,也不是那麼難用的字符串值,將其保存到數據庫等

public enum Profession 
{ 
    Student, 
    WorkingProfessional, 
    Others 
} 

現在:

要檢查是否存在由值的名字在Profession值:

var result = Enum.IsDefined(typeof(Profession), "Retired")); 
// result == false 

爲了得到一個枚舉作爲作爲價值特林:

var result = Enum.GetName(typeof(Profession), Profession.Student)); 
// result == "Student" 

如果實在無法避免使用值名稱用空格或其他特殊字符,你可以使用DescriptionAttribute

public enum Profession 
{ 
    Student, 
    [Description("Working Professional")] WorkingProfessional, 
    [Description("All others...")] Others 
} 

而現在,從Profession價值,你可以使用get描述此代碼(在此處以擴展方法實現):

public static string Description(this Enum e) 
{ 
    var members = e.GetType().GetMember(e.ToString()); 

    if (members != null && members.Length != 0) 
    { 
     var attrs = members.First() 
      .GetCustomAttributes(typeof(DescriptionAttribute), false); 
     if (attrs != null && attrs.Length != 0) 
      return ((DescriptionAttribute) attrs.First()).Description; 
    } 

    return e.ToString(); 
} 

此方法讀取在屬性中定義的描述,如果沒有,則返回的價值名稱。用法:

var e = Profession.WorkingProfessional; 
var result = e.Description(); 
// result == "Working Professional"; 
+0

不,我用這些來解決可讀性問題。這些值最終也會保存到數據庫中。 – Denny 2010-10-22 15:19:21

+0

我編輯了我的答案並詳細闡述了枚舉 - 他們可以在這裏確定。 – NOtherDev 2010-10-23 17:11:46

+0

非常感謝。這真的很有幫助。謝謝!!! = d – Denny 2010-10-29 09:16:39