1
我正在处理一个需要列出和存储某个模型内容并将其添加到列表中的项目。如何从模型列表中获取每个值名称
这里是我的模型:
public class ProductPage
{
public string Name { get; set; }
public string Reference { get; set; }
public string Color { get; set; }
}
这里是我的代码:
public List<TechnicalAttributes> GetAttributeFromProduct(ProductPage product)
{
List<TechnicalAttributes> attributeList = new List<TechnicalAttributes>();
foreach (PropertyInfo pi in product.GetType().GetProperties())
{
if (pi.PropertyType == typeof(string))
{
string value = (string)pi.GetValue(product);
if (!string.IsNullOrEmpty(value))
{
if (!Helper.IsNumeric(value))
{
attributeList.Add(new TechnicalAttributes() { Name = GetVariableName(() => value), Value = value });
}
}
}
}
return attributeList;
}
我的代码让我得到这个:
type = "value" - attribute = "myName"
type = "value" - attribute = "myReference"
type = "value" - attribute = "myColor"
但我想拥有的东西像这样:
type = "Name" - attribute = "myName"
type = "Reference" - attribute = "myReference"
type = "Color" - attribute = "myColor"
我需要使用一个foreach,因为我有更多的参数在我的模型中! 有人可以帮我吗?
我不知道是什么'GetVariableName'是应该做的,但 你需要的是:MemberInfo.Name](https://msdn.microsoft.com/en-us/library/system .reflection.memberinfo.name(v = vs.110).aspx)('PropertyInfo'继承'MemberInfo') –