gpt4 book ai didi

c# - 从 PropertyInfo[] 获取值时如何传递正确的目标

转载 作者:行者123 更新时间:2023-11-30 16:49:33 29 4
gpt4 key购买 nike

在第一个内部循环中,当从 PropertyInfo[] 获取值时,我能够传递正确的目标对象,但是在第二个内部循环中,它给出了目标对象不正确的异常.

所以我想要的是获取具有此 listProperties[j] 内部属性的属性的所有值,如何正确传递目标对象以获取所有这些值?

模型数据:

public class Foo
{
public string Name { get; set; }
public Bar BarProp { get; set; }
}

public class Bar
{
public string Name { get; set; }
public decimal Value { get; set; }
}

方法:

private void CreateDataRow(ISheet sheet, IList iList)
{
for (int i = 0; i < iList.Count; i++)
{

var listType = iList[i].GetType();
var listProperties = listType.GetProperties(BindingFlags.Public | BindingFlags.Instance);

for (int j = 0; j < listProperties.Count(); j++)
{
int columnCount = j;

if (IsPrimitiveType(listProperties[j].PropertyType))
{
var columnData = listProperties[j].GetValue(iList[i], null) ?? "-";
var dataTypeValue = Convert.ChangeType(columnData, listProperties[j].PropertyType);

//omitted codes

continue;
}

var innerProperties = listProperties[j].PropertyType.GetProperties().ToArray();

for (int k = 0; k < innerProperties.Count(); k++)
{
//this throws an exception
var columnData = innerProperties[k].GetValue(listProperties[j], null) ?? "-";

//omitted codes
}
}
}

}

CreateDataRow 在这里被调用:

private XSSFWorkbook CreateWorkbook(T model)
{
var workbook = new XSSFWorkbook();

var type = model.GetType();

var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

foreach (var property in properties)
{
//check if the property is a list
if (property.PropertyType.IsGenericType &&
typeof(List<>).IsAssignableFrom(property.PropertyType.GetGenericTypeDefinition()))
{
var propertyValueList = (IList)property.GetValue(model, null);

if (propertyValueList != null && propertyValueList.Count > 0)
{

//create data row
CreateDataRow(sheet, propertyValueList);
}
}
}
return workbook;
}

T 模型使用此模型:

public class ExportModel
{
public List<Foo> FooList { get; set; }
}

最佳答案

在这行代码中:

var innerProperties = listProperties[j].PropertyType.GetProperties().ToArray(); 

您正在获取 listProperties[j].PropertyType 的属性,但在 GetValue 中:

var columnData = innerProperties[k].GetValue(listProperties[j], null) ?? "-";

您正在发送 listProperties[j] 作为实例参数。更正以下行之一:

var innerProperties = listProperties[j].GetProperties().ToArray();  
//or
var columnData = innerProperties[k].GetValue(listProperties[j].PropertyType, null) ?? "-";

不同的是对象实例和它的类型。 PropertyType 表示检索到的属性的类型,其作用如下:

propertyInfo.GetValue(x,y).GetType();

您应该发送目标对象的确切实例,而不是它的类型,而不是检索到的属性的类型。如果您想获取属性之一的值,请写入:

var columnData = innerProperties[k].GetValue(listProperties[j].GetValue(iList[i],null) ,null) ?? "-";

关于c# - 从 PropertyInfo[] 获取值时如何传递正确的目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36562206/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com