从 C# 中的复杂模型中获取 属性 个值
Get property values from complex model in C#
我想获取复杂模型的属性值 (IList(Object) in object))。我找到了父对象的主要属性以及我需要的子对象的类型。但是我无法提取它的值。
我认为问题出在 GetValue 方法中的对象参数。它必须是 "TheMovieDatabaseModelDetails" 对象。我在这里尝试了很多不同的选项,但出现错误:"object does not match target type".
型号:
public class TheMovieDatabaseModel
{
public int page { get; set; }
public int total_results { get; set; }
public int total_pages { get; set; }
public IList<TheMovieDatabaseModelDetails> results { get; set; }
}
代码:
private async Task GetMovieDetailsForTheMovieDatabase<T>(T movieModel)
{
PropertyInfo[] propertyInfo = movieModel.GetType().GetProperties();
foreach (PropertyInfo property in propertyInfo)
{
if (property.Name.Equals("results"))
{
var movieDetails = property.GetType().GetProperties();
foreach (var detail in movieDetails)
{
detail.GetValue(movieDetails, null); // here I need to fill in the right "object".
}
}
// etc..
}
}
研究(以及其他):
Get Values From Complex Class Using Reflection
我在以下地方找到了答案:
C# object to array
我需要先创建一个 IEnumerable,因为父模型创建了 ChildModel(电影,具有电影细节)的 IList:
if (property.Name.Equals("results"))
{
object movieObject = property.GetValue(movieModel);
IEnumerable movieObjectList = movieObject as IEnumerable;
if (movieObjectList != null)
{
foreach (object movie in movieObjectList)
{
PropertyInfo[] movieDetails = movie.GetType().GetProperties();
foreach (PropertyInfo detail in movieDetails)
{
detail.GetValue(movie, null);
}
}
}
}
我想获取复杂模型的属性值 (IList(Object) in object))。我找到了父对象的主要属性以及我需要的子对象的类型。但是我无法提取它的值。
我认为问题出在 GetValue 方法中的对象参数。它必须是 "TheMovieDatabaseModelDetails" 对象。我在这里尝试了很多不同的选项,但出现错误:"object does not match target type".
型号:
public class TheMovieDatabaseModel
{
public int page { get; set; }
public int total_results { get; set; }
public int total_pages { get; set; }
public IList<TheMovieDatabaseModelDetails> results { get; set; }
}
代码:
private async Task GetMovieDetailsForTheMovieDatabase<T>(T movieModel)
{
PropertyInfo[] propertyInfo = movieModel.GetType().GetProperties();
foreach (PropertyInfo property in propertyInfo)
{
if (property.Name.Equals("results"))
{
var movieDetails = property.GetType().GetProperties();
foreach (var detail in movieDetails)
{
detail.GetValue(movieDetails, null); // here I need to fill in the right "object".
}
}
// etc..
}
}
研究(以及其他): Get Values From Complex Class Using Reflection
我在以下地方找到了答案:
C# object to array
我需要先创建一个 IEnumerable,因为父模型创建了 ChildModel(电影,具有电影细节)的 IList:
if (property.Name.Equals("results"))
{
object movieObject = property.GetValue(movieModel);
IEnumerable movieObjectList = movieObject as IEnumerable;
if (movieObjectList != null)
{
foreach (object movie in movieObjectList)
{
PropertyInfo[] movieDetails = movie.GetType().GetProperties();
foreach (PropertyInfo detail in movieDetails)
{
detail.GetValue(movie, null);
}
}
}
}