c# - 在 C# 中动态访问类及其属性

标签 c#

我需要访问诸如 strClassname.strPropertyName 之类的东西 我将在程序执行中为 strClassnamestrProperty 名称设置不同的值。

请指引我正确的方向。

最佳答案

在我看来,您正试图在运行时获取(或设置)对象的属性值。所以这是执行此操作的最基本方法:

public static object GetPropertyValue(object instance, string strPropertyName)
{
    Type type = instance.GetType();
    System.Reflection.PropertyInfo propertyInfo = type.GetProperty(strPropertyName);
    return propertyInfo.GetValue(instance, null);
}

...并设置一个值:

public static void SetPropertyValue(object instance, string strPropertyName, object newValue)
{
    Type type = instance.GetType();
    System.Reflection.PropertyInfo propertyInfo = type.GetProperty(strPropertyName);
    propertyInfo.SetValue(instance, newValue, null);
}

如果你试图获取一个类的属性名称,这里有一个函数:

public static IEnumerable<string> GetPropertyNames(string className)
{
    Type type = Type.GetType(className);
    return type.GetProperties().Select(p => p.Name);
}

假设您有 100 个对象,并且您想要获取每个对象的 Name 属性的值,这里有一个函数可以完成此操作:

public static IEnumerable<String> GetNames(IEnumerable<Object> objects, string nameProperty = "Name")
{
    foreach (var instance in objects)
    {
        var type = instance.GetType();
        var property = type.GetProperty(nameProperty);
        yield return property.GetValue(instance, null) as string;
    }
}

关于c# - 在 C# 中动态访问类及其属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13985261/

相关文章:

c# - 如何使用 Roslyn 生成类字段的初始化

c# - 任务并解锁用户界面

c# - HRESULT 枚举 C#

c# - 无法使用 Xamarin 在 Android 上创建文件

c# - 当我尝试通过 WinRT 对象从 C++ 调用回调到 C# 时如何解决此 E_POINTER (NullPointerException)?

c# - 访问 RSA key 容器

c# - C#自动添加作者姓名

c# - 如何在 ASP.NET Core 3 中解析本地文件路径?

c# - TFS - 与分支的持续集成

c# - 当 ThreadB Monitor.Pulse(_locker) 哪个线程会先得到 _locker?