C# 具有公共字段的ValueInjector

C# 具有公共字段的ValueInjector,c#,dictionary,valueinjecter,C#,Dictionary,Valueinjecter,如果这是omu.valueinjecter的一个基本特性,我很难理解。 我有两个相同的类(区别主要是名称空间),源类有公共字段而不是公共属性 是否可以使ValueInjector映射公共字段 感谢那些正在寻找复制粘贴解决方案的人: public class PropertyAndFieldInjection : ValueInjection { protected string[] ignoredProps; public PropertyAndFieldInjection()

如果这是omu.valueinjecter的一个基本特性,我很难理解。 我有两个相同的类(区别主要是名称空间),源类有公共字段而不是公共属性

是否可以使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个方向都有效(道具->道具,道具场,场->场)。我没有彻底测试它,因此使用它的风险由您自己承担。

它将属性映射到属性,您需要字段到属性,为此,您可以实现IValueInjection(通过字段/道具循环),并像
target.InjectFrom(源代码)一样使用它