2010-09-07 35 views
0

對於我正在處理的ASP.NET MVC項目,我需要檢查LINQ-To-SQL類中的位變量是否爲真。到目前爲止,檢查每個變量是否爲真或假後,我便推字段的值轉換成一個列表,並返回它像這樣:C#列表/檢查對象變量?

public List<String> GetVarList() { 
    List<String> list = new List<String>(); 

    if (fields.SearchBar) { 
     list.Add("SearchBar"); 
    } 

    if (fields.SomeField) { 
     list.Add("SomeField"); 
    } 

    return list; 
}

這對我來說,似乎並沒有被最快或最簡單的方法來做到這一點。

我想知道它有可能以某種方式通過for或foreach循環遍歷它們來從一個字符串數組中動態檢查變量的值。例如:

public List<String> GetVarList() { 
    String[] array = {"SearchBar", "SomeField"}; 
    List<String> list = new List<String>(); 

    foreach (String field in array) { 
     // Check whether or not the value is true dynamically through the array 
    } 

    return list; 
}

感謝您的任何建議!

+1

您想從最終用戶的角度來完成什麼? – 2010-09-07 20:06:11

回答

0

當然,你可以使用反射這樣的事情:

private bool ValueWasSet(string propertyName) 
{ 
    var property = fields.GetType().GetProperty(propertyName); 
    return (bool)property.GetValue(fields, null); 
} 

public List<string> GetVarList() 
{ 
    return new [] {"SearchBar", "SomeField"} 
     .Where(ValueWasSet) 
     .ToList(); 
} 

這是一個非常直接的解決方案到你想要做的事情,假設你有很多項目要通過。

CAVEAT:這不會比你的代碼更快。你的代碼比這更快......但如果你想更動態地做到這一點,你必須支付輕微的性能價格。

0

您可以使用反射:

public List<String> GetVarList() { 
    String[] array = {"SearchBar", "SomeField"}; 
    List<String> list = new List<String>(); 
    var type=fields.GetType(); 
    foreach (String field in array) { 
     var prop=type.GetProperty(field); 
     if ((bool)prop.GetValue(fields,null)) 
      list.Add(field); 
    } 

    return list; 
} 

從你的問題是不明確的,如果搜索欄,SomeFields等都是字段或屬性。如果他們是領域,相應地更改代碼(使用getfield命令()代替的getProperty())