使用反射提取通用值

时间:2011-07-18 16:50:14

标签: c# reflection

我的项目中有以下界面。

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

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

到目前为止,我已经写了这个,它成功地创建了一个实现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的确切类型?

1 个答案:

答案 0 :(得分:2)

你可以继续这种方法再增加一个间接层:

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