使用反射获取字典值

本文关键字:字典 获取 反射 | 更新日期: 2023-09-27 18:22:06

我正在尝试访问存储在String类型的字典中的对象,UnknownClass。我有这个键,并且知道这个值是几个容器类中的一个。由于值被传递给一个接受对象的方法,所以我不需要知道作为值存储的类的类型。我还需要调用ContainsKey来确认密钥存在。

我尝试了以下方法,但没有成功:

Dictionary<String, object> list = (Dictionary<String, object>)source.GetType().GetProperty(dictionaryName).GetValue(source, null);
nextSource = list[key];

这给了我一个选角错误,并且:

nextSource = source.GetType().GetMethod("get_Item").Invoke(source, new object[] { key });

这给了我一个空引用异常。

这里有更多的代码,尽管我不太确定它会有多大帮助。

private void SetValue(object source, String path, String value)
{
    if (path.Contains('.'))
    {
        //  If this is not the ending Property, continue recursing
        int index = path.IndexOf('.');
        String property = path.Substring(0, index);
        object nextSource;
        if(property.Contains("*"))
        {
            path = path.Substring(index + 1);
            index = path.IndexOf('.');
            String dictionaryName = path.Substring(0, index);
            Dictionary<String, object> list = (Dictionary<String, object>)source.GetType().GetProperty(dictionaryName).GetValue(source, null);
            nextSource = list[property.Substring(1)];
            //property = property.Substring(1);
            //nextSource = source.GetType().GetMethod("Item").Invoke(source, new[] { property });
        } ...

正在访问的字典在PersonObject类中定义如下:

public class PersonObject
{
    public String Name { get; set; }
    public AddressObject Address { get; set; }
    public Dictionary<String, HobbyObject> Hobbies { get; set; }

在此阶段,Path的值被设置为"*Hiking.Hobbies.Hobby"。基本上,路径字符串允许我导航到子类中的属性,并且我需要Dictionary来访问同一类列表的属性。

使用反射获取字典值

字典<TKey,TValue>Class实现了非通用IDictionary接口。因此,如果您有一个tye object变量,其中包含对Dictionary<String, HobbyObject>实例的引用,则可以在字典中检索值,如下所示:

object obj = new Dictionary<String, HobbyObject>
{
    { "Hobby", new HobbyObject() }
};
IDictionary dict = obj as IDictionary;
if (dict != null)
{
    object value = dict["Hobby"];
    // value is a HobbyObject
}

听起来你正在尝试这样做:

var source = new Dictionary<string, object>();
var key = "some key";
source.Add(key, "some value");
var property = source.GetType().GetProperty("Item");
var value = property.GetValue(source, new[] { key });
Console.WriteLine(value.ToString()); // some value

更新:问题是Dictionary<string, HobbyObject>无法转换为Dictionary<string, object>。我认为你必须这样做:

private void SetValue(object source, String path, String value)
{
    if (path.Contains('.'))
    {
        //  If this is not the ending Property, continue recursing
        int index = path.IndexOf('.');
        String property = path.Substring(0, index);
        object nextSource;
        if(property[0] = '*')
        {
            path = path.Substring(index + 1);
            index = path.IndexOf('.');
            String dictionaryName = path.Substring(0, index);
            property = property.Substring(1);
            Object list = source.GetType().GetProperty(dictionaryName)
                                .GetValue(source, null);
            nextSource = list.GetType().GetProperty("Item")
                             .GetValue(list, new[] { property });
        }