通过反射获取类的字段

本文关键字:字段 获取 反射 | 更新日期: 2023-09-27 18:27:39

祝你今天愉快。我试图得到一个类的两个静态字段,但我无法使其工作。我正在尝试获取字段[event]和[adduserlocation]。这是asp.net网页表单的代码隐藏页。任何帮助都非常感谢

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
public partial class test2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var type = typeof(FormBLL).GetType();
        var fieldInfos = type.GetFields(BindingFlags.Instance |
                   BindingFlags.Static |
                   BindingFlags.NonPublic |
                   BindingFlags.Public);
        var q = fieldInfos.ToList();
        foreach(var f in q)
        {
            Response.Write(f.Name + "<br/>");
        }
    }
    public static class FormBLL
    {
        public static string @event = "abc";
        public static string adduserlocation = "123";

    }
}

通过反射获取类的字段

typeof(FormBLL).GetType()就是System.RuntimeType。你不需要GetTypetypeof(FormBLL)足够

var type = typeof(FormBLL);
var fieldInfos = type.GetFields(BindingFlags.Instance |
               BindingFlags.Static |
               BindingFlags.NonPublic |
               BindingFlags.Public);