Warm tip: This article is reproduced from serverfault.com, please click

Why does it get nothing that Getting private Properties? (c#)

发布于 2020-12-05 09:39:31
public class A{
    public Info m_Info = new Info();
    Main()
    {
        Console.WriteLine(m_Info.Property_Count());
    }
    public class Info{

        protected int i_Id;
        protected string s_Name; 

        public int Property_Count(){
            System.Reflection.PropertyInfo[] data = this.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);

            foreach(var item in data)
                Console.WriteLine(item.Name);
            return data.Length;
        }
    }
}

I am trying to get private or protected properties~ but data.Length always return 0, sounds like it get nothing, why it?

Questioner
瓜生真難
Viewed
0
Sweeper 2020-12-05 17:52:09

Your class doesn't have any properties. These:

protected int i_Id;
protected string s_Name; 

are fields. You can either change them to properties:

protected int i_Id { get; set; }
protected string s_Name { get; set; }

or you can use GetFields:

System.Reflection.FieldInfo[] data = this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);