2017-04-21 42 views
3

首先,我读txt文件到一个文件夹,之后我水合使用Expando对象对象的价值。如何得到的expando对象#

但现在我想获得一定的价值,从这个对象,以填补一个ListView(的WinForms)。

private void Form1_Load(object sender, EventArgs e) 
{     
    string pattern = "FAC*.txt"; 
    var directory = new DirectoryInfo(@"C:\\TestLoadFiles"); 
    var myFile = (from f in directory.GetFiles(pattern) 
        orderby f.LastWriteTime descending 
        select f).First(); 

    hydrate_object_from_metadata("FAC",listBox3); 
    hydrate_object_from_metadata("BL", listBox4); 

    this.listBox3.MouseDoubleClick += new MouseEventHandler(listBox3_MouseDoubleClick); 
    this.listBox1.MouseClick += new MouseEventHandler(listBox1_MouseClick); 
} 

void hydrate_object_from_metadata(string tag, ListBox listBox) 
{ 
    SearchAndPopulateTiers(@"C:\TestLoadFiles", tag + "*.txt", tag); 
    int count = typeDoc.Count(D => D.Key.StartsWith(tag)); 

    for (int i = 0; i < count; i++) 
    { 
     object ob = GetObject(tag + i); 
     ///HERE I WOULD LIKE GET DATA VALUE FROM ob object 
    } 
} 

Object GetObject(string foo) 
{ 
    if (typeDoc.ContainsKey(foo)) 
     return typeDoc[foo]; 
    return null; 
} 

void SearchAndPopulateTiers(string path, string extention, string tag) 
{ 
    DirectoryInfo di = new DirectoryInfo(path); 
    FileInfo[] files = di.GetFiles(extention); 

    int i = 0; 
    foreach (FileInfo file in files) 
    { 
     var x = new ExpandoObject() as IDictionary<string, Object>; 

     string[] strArray; 
     string s = ""; 

     while ((s = sr.ReadLine()) != null) 
     { 
      strArray = s.Split('='); 

      x.Add(strArray[0],strArray[1]); 

     } 

     typeDoc.Add(tag+i,x); 
     i++; 
    } 
} 

那么是否有可能在expando对象上获得价值?

+0

您是否试过在“ob”之后放置该属性的名称? I.e var firstName = ob.FirstName;很明显,你不明智。 –

+0

@JohnMc这不适用于'ob',它是一个对象,而不是'ExpandoObject'。 – mason

+0

@mason是的,你是绝对正确的 –

回答

5
var eo = new ExpandoObject(); 
object value = null; 

方法1:动态

dynamic eod = eo; 

value = eod.Foo; 

方法2:IDictionary的

var eoAsDict = ((IDictionary<String, Object>)eo); 

if (eoAsDict.TryGetValue("Foo", out value)) 
{ 
    // Stuff 
} 

foreach (var kvp in eoAsDict) 
{ 
    Console.WriteLine("Property {0} equals {1}", kvp.Key, kvp.Value); 
} 

你不会说什么typeDoc是(是它的另一个ExpandoObject?),但如果你“重新投入x在里面,xExpandoObject,你可以采取x背出来,它仍然是一个。 x在该循环内键入为参考IDictionary<String, Object>的事实既不在此,也不在此。 GetObject()返回object也没关系;一个引用类型为object可以引用任何东西。 GetObject()返回的类型是返回的实际内容中固有的,而不是对它的引用。

因此:

dynamic ob = GetObject(tag + i); 

var ob = GetObject(tag + i) as IDictionary<String, Object>; 

...这取决于你是否更愿意为ob.Fooob["Foo"]访问性能。

+0

'私人词典<字符串,对象> typeDoc = 新词典<字符串,对象>();'我用这个分离我x对象。 – Bissap

+0

@Bissap谢谢。如果你把'typeDoc'放在'ExpandoObjects'中,我会考虑把它改成'Dictionary '。 –

+0

'var ob = GetObject(tag + i)作为IDictionary ;'对我很好! – Bissap