首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有公共字段的ValueInjecter

带有公共字段的ValueInjecter
EN

Stack Overflow用户
提问于 2015-10-27 02:12:26
回答 1查看 183关注 0票数 1

我在低估这是否是omu.valueinjecter的一个基本功能时遇到了麻烦。我有两个相同的类(区别基本上是名称空间),Source类有公共字段,而不是公共属性。

有没有可能让ValueInjecter映射公共字段?

谢谢

EN

回答 1

Stack Overflow用户

发布于 2016-06-09 02:12:31

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

代码语言:javascript
复制
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)。我没有彻底测试它,所以使用它的风险自负。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33352748

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档