如何从PropertyInfo获取属性的值? [英] How do you get the Value of a property from PropertyInfo?

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

问题描述

我有一个具有属性集合的对象.当我得到特定的实体时,我可以看到我正在寻找的字段(opportunityid),并且该字段的Value属性是该机会的Guid.这是我想要的值,但它不会总是有机会,因此我不能总是查看opportunityid,因此我需要根据用户提供的输入来获取该字段.

I've got an object that has a collection of properties. When I get the specific entity I can see the field I'm looking for (opportunityid) and that it's Value attribute is the Guid for this opportunity. This is the value I want, but it won't always be for an opportunity, and therefore I can't always look at opportunityid, so I need to get the field based on input supplied by the user.

到目前为止,我的代码是:

My code so far is:

Guid attrGuid = new Guid();

BusinessEntityCollection members = CrmWebService.RetrieveMultiple(query);

if (members.BusinessEntities.Length > 0)
{
    try
    {
        dynamic attr = members.BusinessEntities[0];
        //Get collection of opportunity properties
        System.Reflection.PropertyInfo[] Props = attr.GetType().GetProperties();
        System.Reflection.PropertyInfo info = Props.FirstOrDefault(x => x.Name == GuidAttributeName);
        attrGuid = info.PropertyType.GUID; //doesn't work.
    }
    catch (Exception ex)
    {
        throw new Exception("An error occurred when retrieving the value for " + attributeName + ". Error: " + ex.Message);
    }
}

动态attr包含我要查找的字段(在本例中为opportunityid),该字段又包含一个值字段,它是正确的Guid.但是,当我获得PropertyInfo信息(opportunityid)时,它不再具有Value属性.我尝试查看PropertyType.GUID,但这没有返回正确的Guid.如何获取此属性的值?

The dynamic attr contains the field I'm looking for (in this case opportunityid), which in turn contains a value field, which is the correct Guid. However, when I get the PropertyInfo info (opportunityid) it no longer has a Value attribute. I tried looking at the PropertyType.GUID but this doesn't return the correct Guid. How can I get the value for this property?

推荐答案

除非属性为static,否则获取PropertyInfo对象不足以获取属性值.当您编写普通" C#时,您需要获取某个属性的值,例如MyProperty,您可以这样编写:

Unless the property is static, it is not enough to get a PropertyInfo object to get a value of a property. When you write "plain" C# and you need to get a value of some property, say, MyProperty, you write this:

var val = obj.MyProperty;

您提供了两件事-属性名称(即获取的内容)和对象(即从何处获取的对象).

You supply two things - the property name (i.e. what to get) and the object (i.e. from where to get it).

PropertyInfo代表什么".您需要分别指定从何处".通话时

PropertyInfo represents the "what". You need to specify "from where" separately. When you call

var val = info.GetValue(obj);

将从哪里"传递到PropertyInfo,让它为您从对象中提取属性的值.

you pass the "from where" to the PropertyInfo, letting it extract the value of the property from the object for you.

注意:在.NET 4.5之前,您需要传递null作为第二个参数:

Note: prior to .NET 4.5 you need to pass null as a second argument:

var val = info.GetValue(obj, null);

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

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