C#:通过反射获得指定类的常亮名称和值

本文介绍了一个需求场景,即如何使用C#的反射将类中的常量值转换为Json或DataSet结构进行输出。主要难点包括识别有效的常量变量、获取变量值以及处理类继承关系。代码示例展示了如何遍历类及其基类的字段,筛选出常量并构造相关信息数据结构。最后,提供了将结果转换为Json或DataSet的方法。
摘要由CSDN通过智能技术生成

摘要:
1、需求场景:我需要把常量值转成属性名输出,需要用反射把相关的变量用Json或者DataSet结构化出来
2、困难点:
(1)怎么识别有效的变量,就单单获得常量,静态变量和普通变量忽略
(2)怎么获得对应的值
(3)类有继承关系,怎么把父类的变量也给输出

原文链接:
http://www.lookdaima.com/page/docItemDetail.html?id=84347696-7f1c-4bd4-ba7d-5d4429f87a48

界面效果:

相关代码:
 

using eKing.LdmWebUtil.Names;
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

public partial class WebForms_Adms_Blanks__Adms_Tools_LdmNameToCode_Default 
    : System.Web.UI.Page
{

    /// <summary>
    /// 
    /// </summary>
    [Serializable]
    public class InfoData
    {
        public InfoData()
        {
        }

        #region TheName ~ 名称

        /// <summary>
        /// TheName ~ 名称
        /// </summary>
        protected string m_TheName = "";

        /// <summary>
        /// TheName ~ 名称
        /// </summary>
        public string TheName
        {
            get
            {
                return m_TheName;
            }
            set
            {
                m_TheName = value;
            }
        }

        #endregion TheName ~ 名称


        #region TheValue ~ 值

        /// <summary>
        /// TheValue ~ 值
        /// </summary>
        protected string m_TheValue = "";

        /// <summary>
        /// TheValue ~ 值
        /// </summary>
        public string TheValue
        {
            get
            {
                return m_TheValue;
            }
            set
            {
                m_TheValue = value;
            }
        }

        #endregion TheValue ~ 值

        #region ExceptionText ~ 异常提示

        /// <summary>
        /// ExceptionText ~ 异常提示
        /// </summary>
        protected string m_ExceptionText = "";

        /// <summary>
        /// ExceptionText ~ 异常提示
        /// </summary>
        public string ExceptionText
        {
            get
            {
                return m_ExceptionText;
            }
            set
            {
                m_ExceptionText = value;
            }
        }

        #endregion ExceptionText ~ 异常提示

    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="theList"></param>
    /// <param name="theName"></param>
    /// <returns></returns>
    public InfoData InfoDataFind(List<InfoData> theList, string theName)
    {
        foreach (InfoData item in theList)
        {
            if (item.TheName == theName)
                return item;
        }

        return null;
    }

    /// <summary>
    /// 通过反射获得所有Field的常用字段
    /// </summary>
    /// <param name="theList"></param>
    /// <param name="thisType"></param>
    protected void ToResultByType(List<InfoData> theList, Type thisType)
    {

        FieldInfo[] fA = thisType.GetFields();

        
        Type typeString = typeof(string);
        InfoData infoDataV = null;
        object oValue = null;

        foreach (FieldInfo fi in fA)
        {
            // 不是字符串类型 //
            if (fi.FieldType != typeString)
                continue;

            // 不是常量 //
            if (!fi.IsStatic)
                continue;

            if (!fi.IsLiteral)
                continue;

            infoDataV = InfoDataFind(theList, fi.Name);

            if (infoDataV != null)
                continue;

            infoDataV = new InfoData();
            infoDataV.TheName = fi.Name;

            try
            {
                oValue = fi.GetValue(null);

                if (oValue == null)
                    infoDataV.TheValue = null;
                else
                    infoDataV.TheValue = oValue.ToString();
            }
            catch(Exception err) 
            {
                infoDataV.ExceptionText = err.Message; 
            }

            theList.Add(infoDataV);
        }


    }

    /// <summary>
    /// 通过反射获得逻辑类的常用值
    /// </summary>
    /// <returns></returns>
    protected string ToResult(string outputType)
    {
        Type thisType = typeof(LdmName);
        List<InfoData> theList = new List<InfoData>();

        while (true)
        {
            if (thisType == null)
                break;

            ToResultByType(theList, thisType);

            thisType = thisType.BaseType;
        }


        if (outputType == "json")
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(theList);
        }

        DataSet ds = new DataSet();
        DataTable dt = new DataTable();

        ds.Tables.Add(dt);

        dt.Columns.Add(new DataColumn("TheName"));
        dt.Columns.Add(new DataColumn("TheValue"));
        dt.Columns.Add(new DataColumn("ExceptionText"));

        DataRow dr = null;

        foreach (InfoData s in theList)
        {
            dr = dt.NewRow();
            dt.Rows.Add(dr);

            dr["TheName"] = s.TheName;
            dr["TheValue"] = s.TheValue;
            dr["ExceptionText"] = s.ExceptionText;
        }

        return ds.GetXml();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        
    }

    protected void btn_DataSet_Click(object sender, EventArgs e)
    {
        txt_Result.Text = ToResult("ds");
    }

    protected void btn_Json_Click(object sender, EventArgs e)
    {
        txt_Result.Text = ToResult("json");
    }
}
using System;
using System.Collections.Generic;
using System.Text;
using eKing.EkWeb.Names;

namespace eKing.LdmWebUtil.Names
{
    /// <summary>
    /// 
    /// </summary>
    public class LdmName
        :
        EkWebConstName
    {
        public LdmName()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            // 
        
        
        }

        /// <summary>
        /// 
        /// </summary>
        public string one = "one";

        /// <summary>
        /// 
        /// </summary>
        public static string two = "two";

        /// <summary>
        /// TheText
        /// </summary>
        public const string TheText = "TheText";

        /// <summary>
        /// TheDescription
        /// </summary>
        public const string TheDescription = "TheDescription";

        

    }
}
using System;
using System.Collections.Generic;

using System.Text;


namespace eKing.EkWeb.Names
{
    /// <summary>
    /// 
    /// </summary>
    public class EkWebConstName
    {
        /// <summary>
        /// 
        /// </summary>
        public EkWebConstName()
        {

        }

        #region PmSlnSort_Id ~ 应用分类

        /// <summary>
        /// PmSlnSort_Id ~ 应用分类
        /// </summary>
        public const string PmSlnSort_Id = "PmSlnSort_Id";

        #endregion PmSlnSort_Id ~ 应用分类


        #region PmBakData_Id ~ 备份记录

        /// <summary>
        /// PmBakData_Id ~ 备份记录
        /// </summary>
        public const string PmBakData_Id = "PmBakData_Id";

        #endregion PmBakData_Id ~ 备份记录


        #region CommentShowFlag ~ 显示注释

        /// <summary>
        /// CommentShowFlag ~ 显示注释
        /// </summary>
        public const string CommentShowFlag = "CommentShowFlag";

        #endregion CommentShowFlag ~ 显示注释
 

    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值