使用反射提取泛型值



我的项目中有以下接口:

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

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

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

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;

接下来我想这样做:(请忽略未定义的变量,您可以假设它们确实存在于我的实际代码中。)

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

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

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

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);

最新更新