How to set Property value using Reflection?

僤鯓⒐⒋嵵緔 提交于 2019-12-11 11:01:49

问题


I try to build a Generic Method which take class and set value using reflection and return a class type.

protected static T GetSecureModel<T>(T model)
        {
            T secureModel = default(T);

            foreach (var property in model.GetType().GetProperties())
            {

                    if (string.CompareOrdinal(property.PropertyType.FullName, "System.String") == 0)
                    {
                        property.SetValue(property.Name, property.GetValue(model, null).ToString(), null);
                    }
             }

              return secureModel;
}

How to return a Class after set value ?


回答1:


OK. I solve it. Check below code, It may be helpful for someone.

   protected static T GetSecureModel<T>(T model)
        {
            bool secureData = false;

            T secureModel = default(T);

            foreach (var property in model.GetType().GetProperties())
            {
                if (property.GetValue(model, null) != null && property.GetValue(model, null).ToString() != _blankGuid && property.GetValue(model, null).ToString() != _zero)
                {
                    if (string.CompareOrdinal(property.PropertyType.FullName, _uniqueIdentifier) == 0)
                    {
                        model.GetType().GetProperty(property.Name).SetValue(model, new Guid(Sanitizer.GetSafeHtmlFragment(property.GetValue(model, null).ToString())), null);
                    }
                    else if (string.CompareOrdinal(property.PropertyType.FullName, _numeric) == 0)
                    {
                        model.GetType().GetProperty(property.Name).SetValue(model, int.Parse(Sanitizer.GetSafeHtmlFragment(property.GetValue(model, null).ToString())), null);
                    }
                    else if (string.CompareOrdinal(property.PropertyType.FullName, _string) == 0)
                    {
                        model.GetType().GetProperty(property.Name).SetValue(model, Sanitizer.GetSafeHtmlFragment(property.GetValue(model, null).ToString()), null);
                    }

                    secureData = true;
                }

            }

            if (secureData)
            {
                secureModel = model;
            }

            return secureModel;
        }


来源:https://stackoverflow.com/questions/14813743/how-to-set-property-value-using-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!