C#。使用反射设置成员对象值

时间:2011-11-13 18:08:45

标签: c# reflection field loops

我需要您的帮助,以下代码。基本上我有一个名为“Job”的类,它有一些公共字段。我传递给我的方法“ApplyFilter”两个参数“job_in”和“job_filters”。第一个参数包含实际数据,第二个参数包含指令(如果有)。我需要遍历“job_in”对象,读取它的数据,通过读取“job_filters”来应用任何指令,修改数据(如果需要)并将其返回到新的“job_out”对象中。一切正常,直到我需要将我的数据存储在“job_out”对象中:

    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;
    }

请帮忙。我通过使用属性看到了一些示例,但我非常确定可以对字段执行相同的操作。谢谢!

2 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:9)

试试这个

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);
        }
    }
}