c# - 使用反射提取通用值

标签 c# reflection

我的项目中有如下界面。

public interface Setting<T>
{
    T Value { get; set; }
}

使用反射,我想检查实现此接口(interface)的属性并提取值。

到目前为止,我已经写了这个,它成功地创建了一个实现设置的属性列表。

var properties = from p in obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
                 where p.PropertyType.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IAplSetting<>))
                 select p;

接下来我想这样做:(请忽略 undefined variable ,你可以假设它们确实存在于我的实际代码中。)

foreach (var property in properties)
{
    dictionary.Add(property.Name, property.GetValue(_theObject, null).Value);
}

问题是 GetValue 返回一个对象。为了访问值,我需要能够转换为 Setting<T> .我如何在不需要知道 T 的确切类型的情况下获取 Value 并存储它?

最佳答案

您可以通过多一层间接来继续这种方法:

object settingsObject = property.GetValue(_theObject, null);
dictionary.Add(
    property.Name,
    settingsObject.GetType().GetProperty("Value")
                            .GetValue(settingsObject, null));

如果您使用的是 dynamic(回复:您对 ExpandoObject 的评论),这会简单得多:

dynamic settingsObject = property.GetValue(_theObject, null);
dictionary.Add(property.Name, settingsObject.Value);

关于c# - 使用反射提取通用值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6736381/

相关文章:

java - 打印类中的所有变量值

java - 列出带有参数和返回类型的类 API

go - 反射(reflection)传递给 interface{} 函数参数的结构

c# - 将控制台应用程序转换为 Windows 服务

c# - 返回日期和时间值的日期类型列

c# - 如何在 MessageBoxIcon.Stop image 等形式上显示图像

c# - 如何通过 WPF Path 对象单击保持 MVVM 模式?

java - 有很多 @Service 方法来检查 id 是否有结果

c# - 从azure中的webjobs读取webapp的web.config

go - go中 `reflect.ValueOf(&x).Elem`和 `reflect.ValueOf(x)`有什么区别?