How can you loop over the properties of a class?

后端 未结 11 1555
温柔的废话
温柔的废话 2020-11-29 23:37

Is there a way in c# to loop over the properties of a class?

Basically I have a class that contains a large number of property\'s (it basically holds the results of

相关标签:
11条回答
  • 2020-11-30 00:23
    foreach (PropertyInfo prop in typeof(MyType).GetProperties())
    {
        Console.WriteLine(prop.Name);
    }
    
    0 讨论(0)
  • 2020-11-30 00:23

    this is how to loop over the properties in vb.net , its the same concept in c#, just translate the syntax:

     Dim properties() As PropertyInfo = Me.GetType.GetProperties(BindingFlags.Public Or BindingFlags.Instance)
                If properties IsNot Nothing AndAlso properties.Length > 0 Then
                    properties = properties.Except(baseProperties)
                    For Each p As PropertyInfo In properties
                        If p.Name <> "" Then
                            p.SetValue(Me, Date.Now, Nothing)  'user p.GetValue in your case
                        End If
                    Next
                End If
    
    0 讨论(0)
  • 2020-11-30 00:26
    string notes = "";
    
    Type typModelCls = trans.GetType(); //trans is the object name
    foreach (PropertyInfo prop in typModelCls.GetProperties())
    {
        notes = notes + prop.Name + " : " + prop.GetValue(trans, null) + ",";
    }
    notes = notes.Substring(0, notes.Length - 1);
    

    We can then write the notes string as a column to the log table or to a file. You have to use System.Reflection to use PropertyInfo

    0 讨论(0)
  • 2020-11-30 00:26

    getting values of properties from simple class object....

    class Person
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public int Age { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var person1 = new Person
            {
                Name = "John",
                Surname = "Doe",
                Age = 47
            };
    
            var props = typeof(Person).GetProperties();
            int counter = 0;
    
            while (counter != props.Count())
            {
                Console.WriteLine(props.ElementAt(counter).GetValue(person1, null));
                counter++;
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-30 00:30
    var csv = string.Join(",",myObj
        .GetType()
        .GetProperties(BindingFlags.Public | BindingFlags.Instance)
        .Select(p => p.GetValue(myObj, null).ToString())
        .ToArray());
    
    0 讨论(0)
提交回复
热议问题