How do you get a property value from PropertyInfo?

I have an object with a set of properties. When I get a specific object, I see the field I'm looking for ( opportunityid ), and that for Guid this Value attribute is Guid . This is the value I want, but it will not always be for opportunity, and therefore I can not always look at opportunityid , so I need to get the field based on the input provided by the user.

My code so far:

 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); } } 

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

+5
source share
4 answers

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

 var val = obj.MyProperty; 

You provide two things - the name of the property (that is, what to get) and the object (i.e. where to get it from).

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

 var val = info.GetValue(obj); 

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

Note: before .NET 4.5, you need to pass null as the second argument:

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

If the property name changes, you should use GetValue :

 info.GetValue(attr, null); 

The last attribute of this method can be null , since this is the index value, and this is only necessary when accessing arrays, for example Value[1,2] .

If you know the name of the attribute in advance, you can use its dynamic behavior: you can call the property without having to do your reflection yourself:

 var x = attr.Guid; 
+3
source

Use PropertyInfo.GetValue() . Assuming your property is of type Guid? then this should work:

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

Note that when invoking a property value, an exception will be thrown.

+2
source

try:

 attrGuid = (Guid)info.GetValue(attr,null) 
+2
source

Source: https://habr.com/ru/post/1204735/


All Articles