2017-05-30 109 views
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,因爲我有更多的參數在我的模型中! 有人可以幫我嗎?

+0

我不知道是什麼'GetVariableName'是應該做的,但 你需要的是:MemberInfo.Name](https://msdn.microsoft.com/en-us/library/system .reflection.memberinfo.name(v = vs.110).aspx)('PropertyInfo'繼承'MemberInfo') –

回答

2

我想你想用pi.Name來得到屬性的名稱。

此屬性是​​的一部分,也可在PropertyInfo。它會給你的財產的名稱。

-1

問題解決了,

你可以有屬性信息的參數的名稱。

pi.Name;