C# 如何在expando对象上获取值

C# 如何在expando对象上获取值,c#,expandoobject,C#,Expandoobject,首先我将txt文件读入文件夹,然后用expando对象水合对象 但是现在我想从这个对象中获取一些值来填充listview winforms private void Form1_Load(object sender, EventArgs e) { string pattern = "FAC*.txt"; var directory = new DirectoryInfo(@"C:\\TestLoadFiles"); var myFile

首先我将txt文件读入文件夹,然后用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对象上获取值吗?

我是以一般/动态方式这样做的,因此没有在代码中包含实际字段名的选项,结果是这样做的:

dynamic eod = eo;

value = eod.Foo;
eo.Where(v => v.Key == keyNameVariable).Select(x => x.Value).FirstOrDefault();

这可能是一种更好的方法,但它很有效。

您是否尝试过在ob之后添加属性名称。即var firstName=ob.firstName;显然,您没有智能感知。@JohnMc这对ob不起作用,ob是一个对象,而不是一个ExpandooObject。@mason是的,您完全正确私有字典类型doc=new Dictionary;我用这个来分隔我的x对象。@Bissap谢谢。如果你把Type对象放入ExpObjObjor,我会考虑把它改成字典。VaBob=GETObjtTAG+I为IDictionary;太好了!