[英]how do I convert Type Object to a List in C# with reflection. I can access the properties in the object but cannot access the values, any suggestions?
我希望能夠遍歷類型為object的通用obj並顯示每個屬性的值。
我已經用谷歌搜索,但是找不到一種方法來訪問對象數組中每個對象的值。
這是一個測試應用程序,可確保API調用返回內容,但我想在UI中顯示數據
當前代碼:
[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;
}
}
}
如果您有扁平物體,可以這樣進行:
foreach (object objl_THIS in lstl_OBJ)
{
var type = objl_THIS.GetType();
var propertyInfos = type.GetProperties();
foreach(var propertyInfo in propertyInfos)
{
string name = propertyInfo.Name;
object value = propertyInfo.GetValue(objl_THIS); // <-- value
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.