How do I iterate through the Attributes of a C# class (.NET 2.0)?
.net-2.0, asp.net, c#, class, json
Solution
To iterate through public instance properties:
Type classType = typeof(TestClass);
foreach(PropertyInfo property in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
Console.WriteLine(property.Name);
}
To iterate through public instance fields:
Type classType = typeof(TestClass);
foreach(FieldInfo field in classType.GetFields(BindingFlags.Public | BindingFlags.Instance))
{
Console.WriteLine(field.Name);
}
If you also want to include non-public properties, add `BindingFlags.NonPublic` to the arguments of `GetProperties` and `GetFields`.
Problem
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 through the Class 'TestClass' and print out public variables and attributes? Remeber .Net2 Thank you