C#通过反射获取到公共静态类中的私有属性中的值
时间: 2024-09-20 18:07:01 浏览: 61
在C#中,反射允许你在运行时动态地检查程序结构,包括访问私有成员。要通过反射获取公共静态类中的私有属性值,你需要创建一个`Assembly`、`Type` 和 `PropertyInfo` 对象,然后使用`GetProperty()`方法以及`GetValue()`方法来读取值。以下是一个简单的示例:
```csharp
using System;
using System.Reflection;
public class MyClass // 公共静态类
{
public static string PrivateValue = "这是私有值"; // 私有属性
}
class Program
{
static void Main(string[] args)
{
try
{
// 获取包含私有属性的类
Type myClassType = Assembly.GetExecutingAssembly().GetType("MyClass");
// 检查是否有名为"PrivateValue"的属性
PropertyInfo privateValueProp = myClassType.GetProperty("PrivateValue", BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
// 如果找到属性,则获取其值
if (privateValueProp != null)
{
object value = privateValueProp.GetValue(null); // 使用null是因为我们处理的是静态属性
Console.WriteLine($"私有属性值: {value}");
}
else
{
Console.WriteLine("无法找到私有属性");
}
}
catch (Exception ex)
{
Console.WriteLine($"反射过程中发生错误: {ex.Message}");
}
Console.ReadLine();
}
}
```
注意,这个例子假设你正在运行的程序与包含`MyClass`的程序位于同一个命名空间内。此外,直接访问私有成员通常被认为是设计模式不当,因为它违反封装原则。反射应谨慎使用,并仅限于那些无法改变源代码的情况。
阅读全文
相关推荐

















