06 Feb 2024
Intermediate
To implement reflection in C#, you typically use classes and methods provided by the System.Reflection namespace. Here are some common tasks and examples of how to use reflection:
-
Retrieve Type Information:
- To get information about a type, you can use the
Typeclass.
Type myType = typeof(MyClass); Console.WriteLine($"Type Name: {myType.Name}, Namespace: {myType.Namespace}"); - To get information about a type, you can use the
-
Inspect Members:
- To inspect members of a type, you can use methods like
GetProperties,GetMethods,GetFields, etc.
foreach (var property in myType.GetProperties()) { Console.WriteLine($"Property: {property.Name}, Type: {property.PropertyType}"); } - To inspect members of a type, you can use methods like
-
Invoke Methods Dynamically:
- To invoke a method dynamically, you can use the
Invokemethod.
object instance = Activator.CreateInstance(myType); MethodInfo myMethod = myType.GetMethod("MyMethod"); myMethod.Invoke(instance, null); - To invoke a method dynamically, you can use the
-
Create Instances Dynamically:
- To create an instance of a type dynamically, you can use the
Activator.CreateInstancemethod.
object instance = Activator.CreateInstance(myType); - To create an instance of a type dynamically, you can use the
-
Work with Attributes:
- To work with custom attributes, you can use the
GetCustomAttributesmethod.
var attributes = myType.GetCustomAttributes(typeof(MyAttribute), true); foreach (var attribute in attributes) { Console.WriteLine($"Attribute: {attribute}"); } - To work with custom attributes, you can use the
Here's a more complete example that demonstrates several aspects of reflection:
using System;
using System.Reflection;
public class MyClass
{
public string MyProperty { get; set; }
public void MyMethod()
{
Console.WriteLine("Executing MyMethod");
}
}
class Program
{
static void Main()
{
Type myType = typeof(MyClass);
// Retrieve type information
Console.WriteLine($"Type Name: {myType.Name}, Namespace: {myType.Namespace}");
// Inspect properties
foreach (var property in myType.GetProperties())
{
Console.WriteLine($"Property: {property.Name}, Type: {property.PropertyType}");
}
// Create an instance and invoke a method
object instance = Activator.CreateInstance(myType);
MethodInfo myMethod = myType.GetMethod("MyMethod");
myMethod.Invoke(instance, null);
}
}
This example covers basic reflection tasks, but keep in mind that reflection has performance implications and should be used carefully. Additionally, error handling is crucial when working with reflection to handle potential exceptions that may occur at runtime.
c-sharp
reflection