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

后端 未结 12 1275
南旧
南旧 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:30

    Have you ever tried to use reflection? Here's a sample code snippet:

    // use reflection to retrieve the values of the following anonymous type
    var obj = new { ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 }; 
    System.Type type = obj.GetType(); 
    int clientid = (int)type.GetProperty("ClientId").GetValue(obj, null);
    string clientname = (string)type.GetProperty("ClientName").GetValue(obj, null);
    
    // use the retrieved values for whatever you want...
    

提交回复
热议问题