您如何从PropertyInfo获得房产的价值?

时间:2014-10-15 12:37:43

标签: c# propertyinfo

我有一个拥有一系列属性的对象。当我获得特定实体时,我可以看到我正在寻找(opportunityid)的字段,并且它的Value属性是此机会的Guid。这是我想要的价值,但它不会永远是一个机会,因此我不能总是看opportunityid,所以我需要根据提供的输入获得该字段用户。

到目前为止我的代码是:

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。我怎样才能获得这个属性的值?

5 个答案:

答案 0 :(得分:29)

除非属性为static,否则获取PropertyInfo对象获取属性值是不够的。当您编写“普通”C#并且需要获取某些属性的值时,比如MyProperty,您可以这样写:

var val = obj.MyProperty;

你提供两件事 - 物业名称(即获得的物品)和物品(即从哪里获得)。

PropertyInfo代表“什么”。您需要单独指定“从哪里”。当你打电话

var val = info.GetValue(obj);

你将“从哪里”传递给PropertyInfo,让它从你的对象中提取属性的值。

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

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

答案 1 :(得分:4)

如果属性名称发生变化,您应该使用GetValue

info.GetValue(attr, null);

该方法的最后一个属性可以是null,因为它是索引值,只有在访问数组时才需要,例如Value[1,2]

如果您事先知道属性的名称,则可以使用它的dynamic行为:您可以调用该属性而无需自己进行反射:

var x = attr.Guid;

答案 2 :(得分:2)

使用PropertyInfo.GetValue()。假设您的属性的类型为Guid?,那么这应该有效:

attrGuid = ((System.Guid?)info.GetValue(attr, null)).Value;

请注意,如果属性值为null,则抛出异常。

答案 3 :(得分:2)

尝试:

attrGuid = (Guid)info.GetValue(attr,null)

答案 4 :(得分:0)

补充一点,这可以通过反射来实现(即使对于未实例化的嵌套类/类型中的属性)

Imports System
Imports System.Reflection

Public Class Program
    Public Shared Sub Main()
        Dim p = New Person()
        For Each nestedtype in p.Gettype().GetNestedTypes()
            For Each prop in nestedtype.GetProperties(BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Static)
                Console.WriteLine(nestedtype.Name & " => " & prop.Name)
            Next
        Next
    End Sub
End Class

Public Class Person
    Public Property Name As String
    Public Property AddressDetail As Address
                    
    Public Class Address                        
        Public Property Street As String
        Public Property CountryDetail As Country
    End Class

    Public Class Country
        Public Property CountryName As String
    End Class                   
End Class

打印以下内容:

地址 => 街道

地址 => 国家详情

国家 => 国家名称

小提琴:https://dotnetfiddle.net/6OsRkp

相关问题