簡體   English   中英

查找對象的屬性並獲取其值-C#

[英]find an object's property and get its value - C#

說有一個像

class phones
{
    public int Id {get; set;}
    public string Name {get; set;}
    public string Color {get; set;}
    public decimal Price {get; set;}
}
List<phones> myList = GetData();
//list is filled with objects

現在,我知道Id和對象屬性的確切名稱,並希望從匹配的對象中獲取值。

private string GetValue(int pid, string featurename)
{
  string val = "";
 foreach(phones obj in myList)
  {
   if(obj.Id == pid)
    {
      //if featurename is 'Name', it should be
      //val = obj.Name;

      //if featurename is 'Price', it should return
      //val = obj.Price;
      break;
    }
  }
  return val;
}

這可能嗎。 請指教。

這個怎么樣:

 foreach(phones obj in myList)
  {
   if(obj.Id == pid)
    {
      if (featurename == "Name")
      {
         return obj.Name;
      }
      else if (featurename == "Price")
      {
         return obj.Price.ToString();
      }
      else
      {
         return string.Empty;
      }
    }
  }

我認為您想要具有給定特征名稱的Property並使用它,您可以使用像這樣的 lambda表達式

要么

像這樣使用PropertyInfo

foreach (PropertyInfo p in typeof(ClassName).GetProperties())
{
    string propertyName = p.Name;
    //....
}

用這個:

 Phones phones= new Phones();          
 string returnValue = phones.GetType().GetProperty(featureName).GetValue(phones, null).ToString();

另外,請記住為輸入的featureName和錯誤處理添加驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM