如何从匿名类型获取属性的值? [英] How can I get a value of a property from an anonymous type?

查看:293
本文介绍了如何从匿名类型获取属性的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由Linq查询填充的数据网格。当数据网格中的焦点行发生变化时,我需要设置一个等于该对象中属性之一的变量。



我尝试过...

  var selectedObject = view.GetRow(rowHandle); 
_selectedId = selectedObject.Id;

...但是编译器根本不关心这一点(嵌入式语句不能是声明或带有标签的声明)。



似乎该属性应该易于访问。在运行时检查对象会显示我期望的所有属性,只是我不知道如何访问它们。



如何获取对匿名对象属性的访问权限? / p>

编辑说明:



我碰巧正在使用DevExpress XtraGrid控件。我用一个Linq查询加载了此控件,该查询由几个不同的对象组成,因此使数据实际上与我已经拥有的任何一个类都不符合(即,我不能将其强制转换为任何对象)。



我正在使用.NET 3.5。



当我查看view.GetRow(rowHandle)方法的结果时,我得到了一个看起来像匿名的类型像这样:

  {ClientId = 7,ClientName = ACME Inc.,乔布斯= 5} 

我的目标是从此匿名类型获取ClientId,以便我可以做其他事情(例如用该客户端加载表单)



我在较早的答案中尝试了一些建议,但无法达到可以获取此ClientId的地步。

解决方案

您是否曾经尝试过使用反射?这是一个示例代码片段:

  //使用反射来获取以下匿名类型的值
var obj = new {ClientId = 7,ClientName = ACME Inc.,Jobs = 5};
System.Type类型= obj.GetType();
int clientid =(int)type.GetProperty( ClientId)。GetValue(obj,null);
字符串clientname =(string)type.GetProperty( ClientName)。GetValue(obj,null);

//将检索到的值用于任何您想要的...


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 tried...

var selectedObject = view.GetRow(rowHandle);
_selectedId = selectedObject.Id;

... but the compiler doesn't care for this at all ("Embedded statement cannot be a declaration or labled statement").

It seems like the property should be easy to access. Inspecting the object during runtime shows all the properties I expect, I just don't know how to access them.

How can I get access to the anonymous object's property?

Edit for Clarifications:

I happen to be using DevExpress XtraGrid control. I loaded this control with a Linq query which was composed of several different objects, therefore making the data not really conforming with any one class I already have (ie, I cannot cast this to anything).

I'm using .NET 3.5.

When I view the results of the view.GetRow(rowHandle) method I get an anonymous type that looks like this:

{ ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 }

My objective is to get the ClientId from this anonymous type so I can do other things (such as a load a form with that client record in it).

I tried a couple of the suggestions in the early answers but was unable to get to a point where I could get this ClientId.

解决方案

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...

这篇关于如何从匿名类型获取属性的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆