本文介绍了C#Reflection虚拟属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我想要使用反射克隆我的模型到ViewModel。



但我的反射功能不能反映虚拟属性,有人可以帮我这个吗?



下面的代码是我用反射克隆的方法: br />


Hello everyone,

I'm want a "clone" my Model to ViewModel using reflection.

But my reflection function cant be reflect Virtual Properties, someone can help me with this?

The code below is my method to "clone" with reflection:

public static D ConvertItem<O, D>(O o)
            where O : class
            where D : class, new()
        {
            D returnValue = new D();

            var typeO = typeof(O);
            var typeD = typeof(D);

            foreach (var item in typeD.GetProperties())
            {
                var prop = typeO.GetProperty(item.Name);

                if (!prop.GetGetMethod().IsVirtual)
                {
                    // NULLABLE PROPERTIES.
                    if (Nullable.GetUnderlyingType(prop.PropertyType) != null)
                    {                        
                        var columnType = prop.PropertyType.GetGenericArguments()[0];

                        if (typeO.GetProperty(item.Name).GetValue(o) != null)
                            item.SetValue(returnValue, Convert.ChangeType(typeO.GetProperty(item.Name).GetValue(o), columnType));
                    }
                    else
                    {
                        // Normal properties.
                        item.SetValue(returnValue, Convert.ChangeType(typeO.GetProperty(item.Name).GetValue(o), item.PropertyType));
                    }
                } 
                else 
                {
                  //HERE, I'AM NEED CALL item.SetValue(...) For VIRTUAL PROPERTIE.
                  //HERE I NEED HELP.
                }

            }

推荐答案


这篇关于C#Reflection虚拟属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 04:58