2013-02-27 85 views
3

我有如果我知道它的字符串名稱,如何爲變量設置值?

public class Rule 
{ 
    public int IdRule { get;set;} 
    public string RuleName { get; set; } 
} 

我哈希表的名單與價值觀。有關鍵的「idRule」,「ruleName」。 例

List<Hashtable> list = new Hashtable(); 
list["idRule"] = 1; 
list["ruleName"] = "ddd"; 

我有功能:

private static List<T> Equaler<T>(T newRule) 
{ 
    var hashTableList = Sql.Table(NameTable.Rules); //Get table from mssql database 
    var list = new List<T>(); 
    var fields = typeof (T).GetFields(); 

    foreach (var hashtable in hashTableList) 
    { 
     var ormRow = newRule; 
     foreach (var field in fields) 
     { 
      ???what write this??? 
      // i need something like 
      //ormRow.SetValueInField(field, hashtable[field.Name]) 

     } 
     list.Add(ormRow); 
    } 
    return list; 
} 

調用此函數:

var rules = Equaler<Rule>(new Rule()) 

問題:如何設定值變量,如果我知道它的字符串名稱?

回答

5

您可以使用反射來做到這一點。

string value = hashtable[field]; 
PropertyInfo property = typeof(Rule).GetProperty(field); 
property.SetValue(ormRow, value, null); 

既然你知道類型是規則,你可以使用typeof(Rule)要獲得類型的對象。但是,如果您在編譯時不知道類型,則還可以使用obj.GetType()來獲取Type對象。還有一個補充性資產PropertyInfo.GetValue(obj, null),它允許您僅通過屬性的'字符串'名稱來檢索值。

參考:http://msdn.microsoft.com/en-us/library/xb5dd1f1.aspx

+0

爲什麼不'typeof運算(規則).GetProperty(場)'呢? – 2013-02-27 05:03:16

+0

@OscarMederos修正並注意到在編譯時和運行時獲取類型對象的區別。 – Despertar 2013-02-27 05:09:50

+0

我的意思是在你的例子中。你仍然在調用'typeof(Rule).GetType()'而不是'typeof(Rule)'。 – 2013-02-27 05:59:22

相關問題