C#反射机制
反射是一种机制,它允许在运行时检查和操作程序集、类、方法、属性等信息的能力。通过反射,可以在运行时获取类型信息、调用方法、访问属性、创建对象实例等操作。
C#反射提供了一组API,包括:
- Type类:表示一个类型或类的元数据信息。
- MethodInfo类:表示一个方法的元数据信息。
- PropertyInfo类:表示一个属性的元数据信息。
- FieldInfo类:表示一个字段的元数据信息。
- Assembly类:表示一个程序集的元数据信息。
- Activator类:用于创建对象实例。
使用C#反射可以实现动态编程、插件式开发、代码生成等功能。例如,可以使用反射来加载和执行指定路径下的DLL文件,或者动态地创建和调用自定义的方法和属性等。
C# 如何获取一个类中的公开的静态属性或者静态成员值
在C#中,可以使用反射来获取一个类中的公开的静态成员值。
例子1:获取动态类的公开的静态成员和静态属性的值
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);
}
}
运行以上代码,将输出:
静态字段的值:10
静态属性的值:Hello World
在上述代码中,我们使用typeof
关键字获取了MyClass
类的Type
对象。然后,使用GetField
方法获取静态字段的FieldInfo
对象,并使用GetValue
方法获取字段的值。同样地,使用GetProperty
方法获取静态属性的PropertyInfo
对象,并使用GetValue
方法获取属性的值。
例子2:从常用画刷集合类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];
}