我无法获取属性在我的模型中IEnumerable属性的名称。我似乎无法从TModel类获得嵌套的IEnumerables。我已经看过一些反思的例子,但并没有像这样的话。来自嵌套IEnumerable的递归属性信息<Model>
我正在寻找只获取每个嵌套模型的IEnumerable属性名称并将属性名称发送到列表。实际值并不重要。
任何帮助将不胜感激。
// TModel = DataContent in this context.
public class GetModelBase<TModel>
{
public string Error { get; set; }
public IEnumerable<TModel> DataContent { get; set; }
}
public class DataContent
{
public int Total { get; set; }
public IEnumerable<Data> Data { get; set; }
}
public class Data
{
public int DataId{ get; set; }
IEnumerable<DataInformation> DataInformation{ get; set; }
}
public IEnumerable<GetModelBase<TModel>> ResponseAsList<TModel>()
{
// ResponseBody in this context is a string representation of json of the models above...
var toArray = new ConvertJsonArray<GetModelBase<TModel>>(ResponseBody).ReturnJsonArray();
}
// T = GetModelBase<DataContent> in this context.
public class ConvertJsonArray<T>
{
public ConvertJsonArray(string responseString)
{
_responseString = responseString;
Convert();
}
public void Convert()
{
var result = JObject.Parse(_responseString);
// This is where I am having trouble... I am unable to get the nested IEnumerable names.
Type t = typeof(T);
PropertyInfo[] propertyInformation = t.GetProperties(BindingFlags.Public|BindingFlags.Instance);
List<string> toLists = new List<string>();
foreach (PropertyInfo pi in propertyInformation)
toLists.Add(pi.Name);
// End of Property Information Issuse...
foreach (string s in toLists.ToArray())
{
if (result[s] != null)
{
if (!(result[s] is JArray)) result[s] = new JArray(result[s]);
}
}
_jsonAsArray = result.ToString();
}
public string ReturnJsonArray()
{
return _jsonAsArray;
}
private string _responseString { get; set; }
private string _jsonAsArray { get; set; }
}
我寻找上面的代码示例中的结果将是只包含了IEnumerable名作为这样的列表{“DataContent”,“数据”,“DataInformation”}
UPDATE:
我仍然无法循环遍历每个模型。我有一个接近工作的代码示例。
// This replaces the Type code in the Convert method...
GetProperties(typeof(T))
private void GetProperties(Type classType)
{
foreach (PropertyInfo property in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (property.PropertyType.IsGenericType && (property.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable<>)))
{
ValuesToList.Add(property.Name);
foreach (Type nestedType in property.PropertyType.GetGenericArguments())
{
GetProperties(nestedType);
}
}
}
}
private List<string> ValuesToList { get; set; }
结果为{“DataContent”,“Data”}但未能获得“DataInformation”。出于某种原因,在foreach循环中IEnumerables不会被击中。额外的帮助将不胜感激。
当我运行样品(至少把它变成一个独立的表格后),我得到'result'中的'Error'和'DataContent'。你的问题是如何识别哪些类型为“IEnumerable <...>'? –
是的,他们应该只显示IEnumerable属性名称,但不仅仅是为ModelBase,而且为DataContent,Data和DataInformation列表。我想从每个嵌套对象中获取所有可能的IEnumerable属性名称。 – user2683328
啊,对 - 我想我把这个例子转换成可编译的东西时,我就杀了这个递归。无论哪种方式,我已经在[我的答案](http://stackoverflow.com/a/43402711/1430156)中解释了所需的过滤条件。 –