C#中的反射應用
目前進行一個小項目的開發,發現需要對類屬性的動態賦值,查MSDN,以反射解決,具體如下:
該項目中有一MODEL類,屬性和數據庫中一個表的字段一一對應,如下:
public class Public_School_table
{
public Public_School_table()
{}
#region Model
private int _id;
private string _institution_name;
private string _institution_type;
private string _mailing_address;
private string _phone;
..................
/// <summary>
///
/// </summary>
public string Institution_Name
{
set{ _institution_name=value;}
get{return _institution_name;}
}
/// <summary>
///
/// </summary>
public string Institution_Type
{
set{ _institution_type=value;}
get{return _institution_type;}
}
/// <summary>
///
/// </summary>
public string Mailing_Address
{
set{ _mailing_address=value;}
get{return _mailing_address;}
}
/// <summary>
///
/// </summary>
public string Phone
{
set{ _phone=value;}
get{return _phone;}
}
..........................
#endregion Model
}
我能從其它地方獲取一個很亂的數據表,與該MODEL的字段並不一一對應,現在的目的是想用這個很亂的數據表去更新數據庫中的數據。
private Model.Public_School_table get_public_school_remark(string html_page, string regex)
{
string _str1,_str2 ;
RegexOptions options = (RegexOptions.Multiline | RegexOptions.IgnoreCase);
Regex reg = new Regex(regex, options);
Model.Public_School_table model = new Model.Public_School_table();
Type type = model.GetType();
MatchCollection mc = reg.Matches(html_page);
foreach (Match ma in mc)
{
_str1 = ma.Groups["1"].Value.ToString().Trim();
_str2 = ma.Groups["2"].Value.ToString().Trim();
foreach (PropertyInfo info in type.GetProperties())
{
if (info.Name == _str1)
{
info.SetValue(model, _str2, null);
}
}
}
return model;
}
很明顯,我已經得到了MODEL,前臺檢查一下,看是否動態賦值了:
Model.Public_School_table model = ws.get_public_school_remark(richTextBox1.Text);
// DataTable table=ws.get_public_school_remark(richTextBox1.Text, "(?<1>[^<>/"/']*):(?<2>[^<>/"/']*)");
// foreach (DataRow dr in table.Rows)
// {
textBox5.Text +="Institution_Name: "+ model.Institution_Name + "/r/n";
textBox5.Text += "Institution_Type: " + model.Institution_Type + "/r/n";
textBox5.Text += "Mailing_Address: " + model.Mailing_Address + "/r/n";
textBox5.Text += "Phone: " + model.Phone + "/r/n";
..........
.....
運行結果:
Institution_Name: Edward R. Murrow High School
Institution_Type: Public School
Mailing_Address: 1600 Avenue LBrooklyn, NY11230
Phone: 718-258-9283
...........
正確無誤,至于效率,有等進一步測試。
當然,也可用其它辦法去實現這外需求,但都很繁瑣,不如Reflection來得簡單。
第一次寫東東,也不知道說明白沒有,也許,自己明白就可以了吧