C# reflection mechanism
Reflection is a mechanism that allows the ability to inspect and manipulate information such as assemblies, classes, methods, properties, etc. at runtime. Through reflection, you can obtain type information, call methods, access properties, create object instances and other operations at runtime.
C# reflection provides a set of APIs, including:
- Type class: Represents metadata information of a type or class.
- MethodInfo class: Represents metadata information of a method.
- PropertyInfo class: Represents metadata information of a property.
- FieldInfo class: Represents metadata information of a field.
- Assembly class: Represents metadata information of an assembly.
- Activator class: used to create object instances.
Using C# reflection can realize dynamic programming, plug-in development, code generation and other functions. For example, you can use reflection to load and execute DLL files under a specified path, or dynamically create and call custom methods and properties.
How to get public static properties or static member values in a class in C#
In C#, you can use reflection to obtain public static member values in a class.
Example 1: Get the values of public static members and static properties of a dynamic class
using System;
using System.Reflection;
public class MyClass
{
public static int MyStaticField = 10;
public static string MyStaticProperty { get; set; } = "Hello World";
public static void Main()
{
Type type = typeof(MyClass);
// 获取静态字段的值
FieldInfo fieldInfo = type.GetField("MyStaticField", BindingFlags.Public | BindingFlags.Static);
int fieldValue = (int)fieldInfo.GetValue(null);
Console.WriteLine("静态字段的值:" + fieldValue);
// 获取静态属性的值
PropertyInfo propertyInfo = type.GetProperty("MyStaticProperty", BindingFlags.Public | BindingFlags.Static);
string propertyValue = (string)propertyInfo.GetValue(null);
Console.WriteLine("静态属性的值:" + propertyValue);
}
}
Running the above code will output:
静态字段的值:10
静态属性的值:Hello World
In the above code, we use typeof
the keyword to get the object MyClass
of the class Type
. Then, use GetField
methods to get FieldInfo
the object of the static field, and GetValue
methods to get the field's value. Likewise, use GetProperty
methods to get objects with static properties PropertyInfo
, and GetValue
methods to get the values of properties.
Example 2: Randomly select a color from the commonly used brush collection class Brushes
private Brush GetRandBrush()
{
Type type = typeof(Brushes);
PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Static);
List<SolidColorBrush> brushes = new List<SolidColorBrush>();
foreach (PropertyInfo prop in props)
{
var brush = prop.GetValue(null) as SolidColorBrush;
if (brush != null)
{
brushes.Add(brush);
}
}
Random rnd = new Random();
int selIdx = rnd.Next(0, brushes.Count);
return brushes[selIdx];
}