-1
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?

  • About fields and properties of a class: https://www.tutorialspoint.com/csharp/csharp_properties.htm and https://www.tutorialsteacher.com/csharp/csharp-class –  Dec 05 '20 at 11:06

1 Answers1

3

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);
Sweeper
  • 213,210
  • 22
  • 193
  • 313