我需要你的幫助,下面的代碼如下。基本上我有一個名爲「Job」的課程,它有一些公共領域。我傳遞給我的方法「ApplyFilter」兩個參數「job_in」和「job_filters」。第一個參數包含實際數據,第二個參數包含說明(如果有的話)。我需要迭代「job_in」對象,讀取它的數據,通過閱讀「job_filters」應用任何指令,修改數據(如果需要)並將其返回到新的「job_out」對象中。C#。使用反射設置成員對象值
public class Job
{
public string job_id = "";
public string description = "";
public string address = "";
public string details = "";
}
...
private Job ApplyFilters(Job job_in, Job job_filters)
{
Type type = typeof(Job);
Job job_out = new Job();
FieldInfo[] fields = type.GetFields();
// iterate through all fields of Job class
for (int i = 0; i < fields.Length; i++)
{
List<string> filterslist = new List<string>();
string filters = (string)fields[i].GetValue(job_filters);
// if job_filters contaisn magic word "$" for the field, then do something with a field, otherwise just copy it to job_out object
if (filters.Contains("$"))
{
filters = filters.Substring(filters.IndexOf("$") + 1, filters.Length - filters.IndexOf("$") - 1);
// MessageBox.Show(filters);
// do sothing useful...
}
else
{
// this is my current field value
var str_value = fields[i].GetValue(job_in);
// this is my current filed name
var field_name = fields[i].Name;
// I got stuck here :(
// I need to save (copy) data "str_value" from job_in.field_name to job_out.field_name
// HELP!!!
}
}
return job_out;
}
請幫助:直到我需要存儲在 「job_out」 對象我的數據一切正常。我已經通過使用屬性看到了一些示例,但我很確定也可以對字段執行相同的操作。謝謝!
賓果!奇蹟般有效。我知道這很簡單!謝謝! :) – Gary