动态访问存储为变量中的字符串的字典元素

时间:2016-05-11 01:37:20

标签: c# dictionary reflection

当元素名称作为字符串存储在变量中时,有没有办法动态访问字典元素?

string field2 = "Entity[\"EmpId\"]";

我尝试访问字符串类型,它按预期工作,但无法理解如何动态获取字典元素值。这是我到目前为止所尝试的。 Demo here

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        Message message = new Message();
        message.EntityId = "123456";

        message.Entity = new Dictionary<string, string>() 
        {
            { "EmpId", "987654"},
            { "DeptId", "10"}
        };

        // Dynamically accessing the field WORKS
        string field1 = "EntityId";
        var v1 = message.GetType().GetProperty(field1).GetValue(message, null); // <-- Works as expected
        Console.WriteLine("EntityId: " + v1.ToString());  // <-- Output: 123456

        // Dynamically accessing a Dictionary element DOESN'T WORK
        string field2 = "Entity[\"EmpId\"]";
        var v2 = message.GetType().GetProperty(field2).GetValue(message, null); // <-- Throws an exception
        //Console.WriteLine("Name: " + v2.ToString());  // <-- Expected Outut: 987654

        Console.WriteLine();
    }

    class Message
    {
        public string EntityId { get; set; }

        // Replacing EntityId with a Dictionary as we have more than one Entities
        public Dictionary<string, string> Entity { get; set; }
    }
}

3 个答案:

答案 0 :(得分:0)

你错误地访问了它。请执行以下操作

string field2 = "Entity";
var v2 = message.GetType().GetProperty(field2).GetValue(message, null) as Dictionary<string, string>;

Console.WriteLine("Name: " + v2["EmpId"]);  // Outut: 987654

答案 1 :(得分:0)

反射不是XML,你必须逐层处理:

// First, get the Entity property, and invoke the getter
var entity = message.GetType().GetProperty("Entity").GetValue(message);
// Second, get the indexer property on it, and invoke the getter with an index(key)
var empId = entity.GetType().GetProperty("Item").GetValue(entity, new[] { "EmpId" });

Console.WriteLine("Name: " + empId);

答案 2 :(得分:0)

可以按照以下方式完成:

//string field2 = "Entity[\"EmpId\"]";
 string f2="Entity";string key="EmpId";
 var v2 =((Dictionary<string,string>)message.GetType().GetProperty(f2).GetValue(message, null))[key]; 

您可以在此处查看https://dotnetfiddle.net/Mobile?id=fc89qQ#code-editor