How to iterate through C # class attributes (.NET 2.0)?

Say I have a class:

public class TestClass
{
  public String Str1;
  public String Str2;
  private String Str3;

  public String Str4 { get { return Str3; } }

  public TestClass()
  {
    Str1 = Str2 = Str 3 = "Test String";
  }
}

Is there a way (C # .NET 2) to iterate the TestClass class and print out public variables and attributes?

Remeber.Net2

thank

+3
source share
4 answers

To iterate through the properties of a public instance:

Type classType = typeof(TestClass);
foreach(PropertyInfo property in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
  Console.WriteLine(property.Name);
}

To iterate over shared instance fields:

Type classType = typeof(TestClass);
foreach(FieldInfo field in classType.GetFields(BindingFlags.Public | BindingFlags.Instance))
{
  Console.WriteLine(field.Name);
}

If you want to include non-public properties, add BindingFlags.NonPublicto the arguments GetPropertiesand GetFields.

+9
source

You can use reflection

TestClass sample = new TestClass();
BindingFlags flags = BindingFlags.Instance | 
    BindingFlags.Public | BindingFlags.NonPublic;

foreach (FieldInfo f in sample.GetType().GetFields(flags))
    Console.WriteLine("{0} = {1}", f.Name, f.GetValue(sample));

foreach (PropertyInfo p in sample.GetType().GetProperties(flags))
    Console.WriteLine("{0} = {1}", p.Name, p.GetValue(sample, null));
+1
source

, .

, .

+1
source

To get type properties, we will use:

Type classType = typeof(TestClass);
    PropertyInfo[] properties = classType.GetProperties(BindingFlags.Public | BindingFlags.Instance);

To get the attributes defined from the class, we will use:

Type classType = typeof(TestClass);
object[] attributes = classType.GetCustomAttributes(false); 

The Boolean flag is passed the Inheritance flag whether to search in the inheritance chain or not.

To get property attributes, we will use:

propertyInfo.GetCustomAttributes(false); 

Using the above Harvard code:

Type classType = typeof(TestClass);
object[] classAttributes = classType.GetCustomAttributes(false); 
foreach(PropertyInfo property in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
  object[] propertyAttributes = property.GetCustomAttributes(false); 
  Console.WriteLine(property.Name);
}
0
source

Source: https://habr.com/ru/post/1731523/


All Articles