Looking at the above example I'm wondering how I can convert the requestedClass
which is of type object
into an array for me to read from.
[HttpGet]
public object Get(string table, string columns, int id)
{
var splitColumns = columns.Split(',');
var t = new propertyModel()
{
gallery = _db.PROPERTYGALLERies.Where(p => p.propertyId == id).ToList(),
property = _db.PROPERTies.SingleOrDefault(p => p.id == id)
};
var requestedClass = t.GetType().GetProperty(table.ToLower()).GetValue(t, null);
var returnArray = new Dictionary<string, List<string>>();
var requestArray = new List<string>();
foreach (var column in splitColumns)
{
foreach (var field in StringProperties(requestedClass, column))
{
requestArray.Add(field.Value);
}
}
returnArray.Add(table, requestArray);
return Json(returnArray, JsonRequestBehavior.AllowGet);
}
public IEnumerable<KeyValuePair<string, string>> StringProperties(object obj, string column)
{
return from p in obj.GetType().GetProperties()
where p.Name == column
select new KeyValuePair<string, string>(p.Name, Convert.ToString(p.GetValue(obj)));
}
You can just cast it to whatever the proper underlying type is. If the object is actually, for instance, an instance of DataObject[]
you can just do:
DataObject[] mydataObjectArray = (DataObject[])requestedClass;
And you should be all set. Keep in mind, DataObject
is just a made up class I am using to illustrate the concept. Whatever requestedClass
was originally before it was cast as an object
is what you will need to cast it to.
It depends on what you know about the object at compile-time. If all you know is that it's an IEnumerable<>
, you should be able to cast it like this:
object[] values = ((IEnumerable<object>)requestedClass).ToArray();
If you also know that it always contains Data.PROPERTYGALLERY
objects, you could cast the items to end up with a more strongly-typed array:
Data.PROPERTYGALLERY[] values = ((IEnumerable<object>)requestedClass)
.Cast<Data.PROPERTYGALLERY>()
.ToArray();
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.