C#. Set a member object value using reflection

前端 未结 2 1061
别跟我提以往
别跟我提以往 2020-12-16 07:20

I need your help with the following code below. Basically I have a class called \"Job\" which has some public fields. I\'m passing to my method \"ApplyFilter\" two parameter

相关标签:
2条回答
  • 2020-12-16 07:55

    Try this

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-16 07:59
    fields[i].SetValue(job_out, str_value);
    
    0 讨论(0)
提交回复
热议问题