I want to use the reflection to get the value from a class object. In this case, Rating is my main class which contains a property of Contribution class.
Following is the structure of my class
public class Rating
{
public string personal_client_id { get; set; }
public string risk_benefit_id { get; set; }
public string type { get; set; }
public string risk_event { get; set; }
public string value { get; set; }
public Contribution contribution { get; set; }
}
public class Contribution
{
public string from { get; set; }
public string value { get; set; }
}
Now I want the value from the contribution property like below.
var Rating = RatingObject.Where(x => x.personal_client_id == pcid).FirstOrDefault();
if (Rating != null)
{
Type type = Rating.GetType();
PropertyInfo propertyInfo = type.GetProperty("contribution");
var aa = propertyInfo.GetValue(Rating, null);
//aa has the Contribution property now but i don't know how can i get the property value from
this object
//Remember i dont want to do this **((Contribution)(aa)).from**
}
else
{
return "";
}
Please help!
Given you already have the rating
object, you could define a PropertyInfo
for the property you want to read from the Contribuition
type and use the reference on the rating.contribution
to read it. For sample
PropertyInfo propertyInfo = typeof(Rating).GetProperty("contribution");
var contribution = propertyInfo.GetValue(rating, null) as Contribution;
if (contribution != null)
{
Console.WriteLine(contribution.from);
Console.WriteLine(contribution.value);
}
Remember that PropertyInfo.GetValue
method returns an something from object
type, so, you have to cast it to the expected type.
Instead of using var, you can force the type of aa to be a dynamic.
dynamic aa = propertyInfo.GetValue(Rating, null);
return aa.from;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.