Leveraging Reflection to Access C# Class Properties
Object-oriented programming frequently requires interacting with class instances and their properties. Reflection offers a powerful mechanism for dynamically examining and manipulating these properties. This guide demonstrates how to retrieve a list of properties associated with a class.
Retrieving Property Information
The .NET Reflection API simplifies property exploration. Two primary methods achieve this:
Obj.GetType().GetProperties()
: Used when working with a specific class instance.typeof(ClassName).GetProperties()
: Used when working directly with the class type.Both methods yield an array of PropertyInfo
objects, each representing a single property of the class.
Practical Example
Let's illustrate with a sample class:
<code class="language-csharp">public class Foo { public int A { get; set; } public string B { get; set; } }</code>
The following code snippet retrieves and displays the values of all properties of a Foo
instance:
<code class="language-csharp">Foo foo = new Foo { A = 1, B = "abc" }; foreach (var prop in foo.GetType().GetProperties()) { Console.WriteLine($"{prop.Name} = {prop.GetValue(foo)}"); }</code>
Important Notes:
null
as the second argument to GetValue()
.GetProperties(BindingFlags)
with appropriate flags like BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
. Remember that accessing non-public members should be done cautiously and only when absolutely necessary.The above is the detailed content of How Can I Use Reflection to Explore Class Properties in C#?. For more information, please follow other related articles on the PHP Chinese website!