How can I get a value of a property from an anonymous type?

后端 未结 12 1270
南旧
南旧 2020-12-24 08:34

I have a datagrid populated by a Linq query. When the focused row in the datagrid changes I need to set a variable equal to one of the properties in that object.

I t

12条回答
  •  佛祖请我去吃肉
    2020-12-24 09:21

    When I was working with passing around anonymous types and trying to recast them I ultimately found it easier to write a wrapper that handled working with the object. Here is a link to a blog post about it.

    http://somewebguy.wordpress.com/2009/05/29/anonymous-types-round-two/

    Ultimately, your code would look something like this.

    //create an anonymous type
    var something = new {  
      name = "Mark",  
      age = 50  
    };  
    AnonymousType type = new AnonymousType(something);
    
    //then access values by their property name and type
    type.With((string name, int age) => {  
      Console.Write("{0} :: {1}", name, age);  
    }); 
    
    //or just single values
    int value = type.Get("age");   
    

提交回复
热议问题