how do I iterate through internal properties in c#

前端 未结 6 1172
鱼传尺愫
鱼传尺愫 2020-12-30 23:07
public class TestClass
{
        public string property1 { get; set; }
        public string property2 { get; set; }

        internal string property3 { get; set; }         


        
6条回答
  •  一个人的身影
    2020-12-30 23:28

    You get the internal properties of a type by querying the NonPublic properties and then filtering the Get methods of these by "IsAssembly".

    "internal protected" properties have their getters marked as "IsFamilyOrAssembly", "protected" properties as "IsFamily", and "private" properties as marked with "IsPrivate":

        public class TestClass
        {
            public string Property1 { get; set; }
            private string Property2 { get; set; }
    
            public string Property9 { get; set; }
            private string Property10 { get; set; }
    
            protected internal string Property3 { get; set; }
            protected string Property4 { get; set; }
            internal string Property5 { get; set; }
    
            protected internal int Property6 { get; set; }
            protected int Property7 { get; set; }
            internal int Property8 { get; set; }
    
            internal static void ShowPropertyAccessScope(Type t)
            {
    
                foreach (var prop in t.GetProperties(BindingFlags.Instance | BindingFlags.Public))
                {
                    Console.WriteLine("{0,-28} {1,15}", "Public property:", prop.Name);
                }
    
                var nonPublic = t.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic);
    
                foreach (var prop in nonPublic.Where(p => p.GetGetMethod(true)?.IsAssembly == true))
                {
                    Console.WriteLine("{0,-28} {1,15}", "Internal property:", prop.Name);
                }
    
                foreach (var prop in nonPublic.Where(p => p.GetGetMethod(true)?.IsFamilyOrAssembly == true))
                {
                    Console.WriteLine("{0,-28} {1,15}", "Internal protected property:", prop.Name);
                }
    
                foreach (var prop in nonPublic.Where(p => p.GetGetMethod(true)?.IsFamily == true))
                {
                    Console.WriteLine("{0,-28} {1,15}", "Protected property:", prop.Name);
                }
    
                foreach (var prop in nonPublic.Where(p => p.GetGetMethod(true)?.IsPrivate == true))
                {
                    Console.WriteLine("{0,-28} {1,15}", "Private property:", prop.Name);
                }
            }
            static void Main() 
            {
                ShowPropertyAccessScope(typeof(TestClass));
            }
        }
    

提交回复
热议问题