Reflections -Set of objects when property is in list <>

I know that I can use reflection to set a property of objects like below.

    public void SaveContent(string propertyName, string contentToUpdate, string corePageId)
    {
        var page = Session.Load<CorePage>(corePageId);
        Type type = page.GetType();
        PropertyInfo prop = type.GetProperty(propertyName);
        prop.SetValue(page, contentToUpdate, null);
    }

      

I have the following classes below:

public class CorePage
{
    public string BigHeader { get; set; }
    public List<BigLinks> BigLinks { get; set; }
}

 public class BigLinks
{
    public string TextContent { get; set; }
}

      

My SaveContent()

-method works, obviously when the property to be set is, for example, public string BigHeader { get; set; }

But how can I do this if the property I want to set is in the property:

public List<BigLinks> BigLinks { get; set; }

      

If public List<BigLinks> BigLinks { get; set; }

is a list of 5 BigLinks

objects, how can the value of, for example, third objects be set public string TextContent { get; set; }

?

+3


source share


1 answer


You have to get the property value using reflection and change the desired value like this:

var c = new CorePage() { BigLinks = new List<BigLinks> { new BigLinks { TextContent = "Y"}}};
var r = typeof(CorePage).GetProperty("BigLinks").GetGetMethod().Invoke(c, null) as List<BigLinks>;
    r[0].TextContent = "X";

      

If you don't know the type of the list item:



var itemInList = (typeof(CorePage).GetProperty("BigLinks").GetGetMethod().Invoke(c, null) as IList)[0];
itemInList.GetType().GetProperty("TextContent").SetValue(itemInList, "XXX", null);

      

Another option is to switch to dynamic:

var itemInList = (typeof(CorePage).GetProperty("BigLinks").GetGetMethod().Invoke(c, null) as dynamic)[0].TextContent = "XXXTTT";

      

+1


source







All Articles