2011-11-13 49 views
3

我需要你的幫助,下面的代碼如下。基本上我有一個名爲「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」 對象我的數據一切正常。我已經通過使用屬性看到了一些示例,但我很確定也可以對字段執行相同的操作。謝謝!

回答

7
fields[i].SetValue(job_out, str_value); 
+1

賓果!奇蹟般有效。我知道這很簡單!謝謝! :) – Gary

7

試試這個

public static void MapAllFields(object source, object dst) 
{ 
    System.Reflection.FieldInfo[] ps = source.GetType().GetFields(); 
    foreach (var item in ps) 
    { 
     var o = item.GetValue(source); 
      var p = dst.GetType().GetField(item.Name); 
      if (p != null) 
      { 
       Type t = Nullable.GetUnderlyingType(p.FieldType) ?? p.FieldType; 
       object safeValue = (o == null) ? null : Convert.ChangeType(o, t); 
       p.SetValue(dst, safeValue); 
      } 
    } 
} 
+3

您可能不需要對'o'進行第二次空檢查。不過,這裏有一些很好的防守編碼。 – JRoughan

+1

@JRoughan是對的;你在'safeValue'的賦值中處理'o == null'的情況,所以不需要檢查上面的內容。 –

+0

是的你是對的 – DeveloperX