带有公共字段的valueinjector

本文关键字:valueinjector 字段 | 更新日期: 2023-09-27 18:19:15

我很难理解这是否是omu. valueinjector的基本功能。我有2个相同的类(区别基本上是名称空间)和源类有公共字段,而不是公共属性。

是否有可能使valueinjector映射公共字段?

谢谢

带有公共字段的valueinjector

对于那些需要复制粘贴解决方案的人:

public class PropertyAndFieldInjection : ValueInjection
{
    protected string[] ignoredProps;
    public PropertyAndFieldInjection()
    {
    }
    public PropertyAndFieldInjection(string[] ignoredProps)
    {
        this.ignoredProps = ignoredProps;
    }
    protected override void Inject(object source, object target)
    {
        var sourceProps = source.GetType().GetProps();
        foreach (var sourceProp in sourceProps)
        {
            Execute(sourceProp, source, target);
        }
        var sourceFields = source.GetType().GetFields();
        foreach (var sourceField in sourceFields)
        {
            Execute(sourceField, source, target);
        }
    }
    protected virtual void Execute(PropertyInfo sp, object source, object target)
    {
        if (!sp.CanRead || sp.GetGetMethod() == null || (ignoredProps != null && ignoredProps.Contains(sp.Name)))
            return;
        var tp = target.GetType().GetProperty(sp.Name);
        if (tp != null && tp.CanWrite && tp.PropertyType == sp.PropertyType && tp.GetSetMethod() != null)
        {
            tp.SetValue(target, sp.GetValue(source, null), null);
            return;
        }
        var tf = target.GetType().GetField(sp.Name);
        if (tf != null && tf.FieldType == sp.PropertyType)
        {
            tf.SetValue(target, sp.GetValue(source, null));
        }
    }
    protected virtual void Execute(FieldInfo sf, object source, object target)
    {
        if (ignoredProps != null && ignoredProps.Contains(sf.Name))
            return;
        var tf = target.GetType().GetField(sf.Name);
        if (tf != null && tf.FieldType == sf.FieldType)
        {
            tf.SetValue(target, sf.GetValue(source));
            return;
        }
        var tp = target.GetType().GetProperty(sf.Name);
        if (tp != null && tp.CanWrite && tp.PropertyType == sf.FieldType && tp.GetSetMethod() != null)
        {
            tp.SetValue(target, sf.GetValue(source), null);
        }
    }
}

这适用于所有4个方向(prop->prop, prop<->field, field->field)。我没有对它进行彻底的测试,所以使用它的风险由你自己承担。