How to access property of anonymous type in C#?

后端 未结 5 1066
南旧
南旧 2020-11-28 02:40

I have this:

List nodes = new List(); 

nodes.Add(
new {
    Checked     = false,
    depth       = 1,
    id          = \"div_\"         


        
      
      
      
5条回答
  •  爱一瞬间的悲伤
    2020-11-28 02:53

    You could iterate over the anonymous type's properties using Reflection; see if there is a "Checked" property and if there is then get its value.

    See this blog post: http://blogs.msdn.com/wriju/archive/2007/10/26/c-3-0-anonymous-type-and-net-reflection-hand-in-hand.aspx

    So something like:

    foreach(object o in nodes)
    {
        Type t = o.GetType();
    
        PropertyInfo[] pi = t.GetProperties(); 
    
        foreach (PropertyInfo p in pi)
        {
            if (p.Name=="Checked" && !(bool)p.GetValue(o))
                Console.WriteLine("awesome!");
        }
    }
    

提交回复
热议问题