C# 反射取得类的属性名、类型、值


今天勇哥有一段代码遇到这个需求,即把数据库表的实体类的属性名字与其值显示到UI上去。

在网上找到几个函数,解决了问题。


  /// <summary>
        /// 获取类中的属性值
        /// </summary>
        /// <param name="FieldName"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string GetModelValue(string FieldName, object obj)
        {
            try
            {
                var 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;
            }
        }

        /// <summary>
        /// 设置类中的属性值
        /// </summary>
        /// <param name="FieldName"></param>
        /// <param name="Value"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool SetModelValue(string FieldName, string Value, object obj)
        {
            try
            {
                var Ts = obj.GetType();
                object v = Convert.ChangeType(Value, Ts.GetProperty(FieldName).PropertyType);
                Ts.GetProperty(FieldName).SetValue(obj, v, null);
                return true;
            }
            catch
            {
                return false;
            }
        }


下面再放上另一个程序,它还可以读到属性为List类型的值,这样的复杂情况。

image.png

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

         void FromatDitits<T>(T model)
        {
            var newType = model.GetType();
            foreach (var item in newType.GetProperties())
            {
                var type = item.PropertyType.Name;
                var IsGenericType = item.PropertyType.IsGenericType;
                var list = item.PropertyType.GetInterface("IEnumerable", false);
                //richTextBox1.AppendText($"属性名称:{item.Name},类型:{type},值:{item.GetValue(model)}");
                if (IsGenericType && list != null)
                {
                    var listVal = item.GetValue(model) as IEnumerable<object>;
                    if (listVal == null) continue;
                    foreach (var aa in listVal)
                    {
                        var dtype = aa.GetType();
                        foreach (var bb in dtype.GetProperties())
                        {
                            var dtlName = bb.Name.ToLower();
                            var dtlType = bb.PropertyType.Name;
                            var oldValue = bb.GetValue(aa);
                            if (dtlType == typeof(decimal).Name)
                            {
                                int dit = 4;
                                if (dtlName.Contains("price") || dtlName.Contains("amount"))
                                    dit = 2;
                                bb.SetValue(aa, Math.Round(Convert.ToDecimal(oldValue), dit, MidpointRounding.AwayFromZero));
                            }
                            richTextBox1.AppendText(string.Format("子级属性名称:{0},类型:{1},值:{2}\r\n", 
                                dtlName, dtlType, oldValue));
                        }
                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var model = new Product
            {
                Id = "222",
                Name = "Test1",
                Detail = new List<ProductDetail>
                {
                    new ProductDetail{Id="111" ,DtlId="1",Number=12.3568M,Price=5.689M,Amount=70.2978352M},
                    new ProductDetail{Id="111",DtlId="2",Number=12.35M,Price=5.689M,Amount=70.2978352M},
                    new ProductDetail{Id="111",DtlId="3",Number=12.358M,Price=5.689M,Amount=70.304662M},
                }
            };
            FromatDitits<Product>(model);
            richTextBox1.AppendText("----------------------------\r\n");
         
            foreach (var item in model.Detail)
            {
                richTextBox1.AppendText(string.Format("Number值为:{0},Price值为:{1},Amount值为:{2}\r\n"
                    ,item.Number,item.Price,item.Amount));
            }

            
        }
    }

    class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public List<ProductDetail> Detail { get; set; }
        public List<ProductComment> Comment { get; set; }
    }
    class ProductDetail
    {
        public string DtlId { get; set; }
        public string Id { get; set; }
        public decimal Number { get; set; }
        public decimal Price { get; set; }
        public decimal Amount { get; set; }
    }
    class ProductComment
    {
        public string DtlId { get; set; }
        public string Id { get; set; }
        public string Comment { get; set; }
    }


}

--------------------- 

作者:hackpig
来源:
www.skcircle.com
版权声明:本文为博主原创文章,转载请附上博文链接!


本文出自勇哥的网站《少有人走的路》wwww.skcircle.com,转载请注明出处!讨论可扫码加群:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

会员中心
搜索
«    2024年4月    »
1234567
891011121314
15161718192021
22232425262728
2930
网站分类
标签列表
最新留言
    热门文章 | 热评文章 | 随机文章
文章归档
友情链接
  • 订阅本站的 RSS 2.0 新闻聚合
  • 扫描加本站机器视觉QQ群,验证答案为:halcon勇哥的机器视觉
  • 点击查阅微信群二维码
  • 扫描加勇哥的非标自动化群,验证答案:C#/C++/VB勇哥的非标自动化群
  • 扫描加站长微信:站长微信:abc496103864
  • 扫描加站长QQ:
  • 扫描赞赏本站:
  • 留言板:

Powered By Z-BlogPHP 1.7.2

Copyright Your skcircle.com Rights Reserved.

鄂ICP备18008319号


站长QQ:496103864 微信:abc496103864