jeudi 24 janvier 2019

how do I convert Type Object to a List in C# with reflection

I want to be able to loop through a generic obj of type object and display the value of each property.

I have googled but can't find a way to access the value of each Object in a object array.

This is a test application to make sure an API call returns stuff, but i want to display the data in the UI

Current code:

[Route("Home/Index/")]
[HttpPost]
public string Index(string strv_Params, string strv_Method)
{

  try
  {
    #region Region Create a new instance of the assebly

    //Declare the assembly
    Assembly executingAssebbly = AppDomain.CurrentDomain.GetAssemblies().Where(x => x.FullName.Contains("DLL_Example")).FirstOrDefault();       
    Type customerType = executingAssebbly.GetType("CLASS_EXAMPLE");

    //Assebly calls the new constructor
    object customerInstance = Activator.CreateInstance(customerType);

    //I need to call a mathod that is used like a construcor to set some globle varables
    MethodInfo setStartupProperties = customerType.GetMethod("METHOD_NAME_EXAMPLE");

    //Params needed in the construtor
    object[] PropertySettings = new object[3];
    PropertySettings[0] = "PropertySettings";
    PropertySettings[1] = "PropertySettings";
    PropertySettings[2] = "PropertySettings";

    //Call the Constructor to set up the assebly
    setStartupProperties.Invoke(customerInstance, PropertySettings);  
    #endregion

    //Build up a Property array from the UI
    #region Region Buiild My Params

    List<string> thesplit = new List<string>();

    foreach (var item in strv_Params.Split(','))
    {
      var ahh = item.Split('|');
      thesplit.Add(ahh[1]);
    }

    int count = thesplit.Count();
    object[] paramters = new object[count];

    int li = 0;
    foreach (var item in thesplit)
    {
      if (item == "Ref")
      {
        paramters[li] = "";
      }
      else
      {
        paramters[li] = item;
      }
      li++;

    }
    #endregion

    //Declare the Method info using the string passed from the UI
    MethodInfo GetFullNameMathod = customerType.GetMethod(strv_Method);

    //Call the method using reflection with the params passing in from the UI
    object retur = GetFullNameMathod.Invoke(customerInstance, paramters);

    //Converts object to list of objects
    object[] arr_obj = (object[])retur;        
    IEnumerable<object> lstl_OBJ = arr_obj.ToList();

    string htmlReturn = "";       

    foreach (object objl_THIS in lstl_OBJ)
    {
      //here I want to access each value in objl_THIS
    }

    return htmlReturn;
  }

  catch (Exception ex)
  {
    return ex.Message;
  }
}

}





Aucun commentaire:

Enregistrer un commentaire