开发者

Reflection GetFields can't retrieve value from asp.net but console

开发者 https://www.devze.com 2023-03-06 05:37 出处:网络
Here is my code sni开发者_如何学Pythonppet Console App (works fine) class Program { private string Val;

Here is my code sni开发者_如何学Pythonppet

Console App (works fine)

class Program
{
    private string Val;

    static void Main(string[] args)
    {
        Program p = new Program();
        p.Test();
    }

    private void Test()
    {
        var t = GetType();

        const BindingFlags flag = BindingFlags.DeclaredOnly | 
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

        foreach (var fieldInfo in t.GetFields(flag))
        {
            Console.WriteLine(fieldInfo.Name);
        }
    }
}

Web app (not working)

public class BasePage:Page
{
    protected override void OnLoad(EventArgs e)
    {
        var t = GetType();

        const BindingFlags flag = BindingFlags.DeclaredOnly | 
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

        foreach (FieldInfo item in t.GetFields(flag))
        {
            System.Diagnostics.Debug.Write(item.Name);
        }

        base.OnLoad(e);
    }  
}

Test code

public partial class _Default : BasePage
{
    private string ABC;
    public string Good { get; set; }

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


GetType will not return _Default class, but a class generated by ASP.net that inherits _Default. try GetType().BaseType or typeof(_Default).

Edit:

Also make _Default inherit from BasePage instead of Page or else the entire reflection logic would not even be includes in _Default

0

精彩评论

暂无评论...
验证码 换一张
取 消