我的项目中有如下界面。
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/