2016-05-11 8 views
0

変数に文字列として要素名が格納されている場合、辞書要素に動的にアクセスする方法はありますか?変数に文字列として格納されている辞書要素に動的にアクセスする

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

答えて

0

あなたは間違ってアクセスしています。次

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

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

OPは**動的に**辞書要素にアクセス**を求めています。あなたはそれを直接行いました。 – Xiaoy312

+0

キャストが望ましくないかどうかは既に分かっています。 – SirH

+0

OPはXMLセレクタを介してオブジェクトにアクセスしたかったようですが、これはいくつかの魔法のトリックなしでは動作しません。 – Xiaoy312

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

関連する問題