开发者

Extract a generic value using reflection

I have the following interface in my project.

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

Using reflection, I would like to exa开发者_StackOverflow社区mine properties that implement this interface and extract Value.

So far I have written this, which successfully creates a list of properties that implement 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;

Next I would like to do this: (Please ignore the undefined variables, you can assume that they really do exist in my actual code.)

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

The problem is that GetValue returns an object. In order to access Value, I need to be able to cast to Setting<T>. How would I get Value and store it, without needing to know the exact type of T?


You could continue this approach with one more level of indirection:

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

If you're using dynamic (re: your comment about ExpandoObject), this can be much simpler:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜