[轉] C#反射設置屬性值和獲取屬性值

 

        /// 
        /// 獲取類中的屬性值
        /// 
        /// 
        /// 
        /// 
        public string GetModelValue(string FieldName, object obj)
        {
            try
            {
                Type Ts = obj.GetType();
                object o = Ts.GetProperty(FieldName).GetValue(obj, null);
                string Value = Convert.ToString(o);
                if (string.IsNullOrEmpty(Value)) return null;
                return Value;
            }
            catch
            {
                return null;
            }
        }

        /// 
        /// 設置類中的屬性值
        /// 
        /// 
        /// 
        /// 
        public bool SetModelValue(string FieldName,string Value, object obj)
        {
            try
            {
                Type Ts = obj.GetType();
                object v = Convert.ChangeType(Value, Ts.GetProperty(FieldName).PropertyType);
                Ts.GetProperty(FieldName).SetValue(obj, v, null);
                return true;
            }
            catch
            {
                return false;
            }
        }

 

在網上找沒有找到,剛本身寫了一個方法,供分享..net

在寫方法時這裏有一個東西弄了好久沒有搞好.就是屬性類型若是是int 時,傳入string字串就會設置不成功.code

這裏我用到了Convert.ChangeType 轉換,根據屬性類型自動轉換.blog

轉自:http://blog.csdn.net/cestarme/article/details/6548126get

相關文章
相關標籤/搜索