C#. Set a member object value using reflection

前端 未结 2 1123
别跟我提以往
别跟我提以往 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);
            }
        }
    }
    

提交回复
热议问题