是否有内置的.NET方法来获取对象的所有属性和值?

时间:2010-04-28 15:13:12

标签: c# .net

让我说我有:

public class Item
{
    public string SKU {get; set; }
    public string Description {get; set; }
}

....

.NET中是否有内置方法可以让我获取类型为i的变量Item的属性和值,如下所示:

{SKU: "123-4556", Description: "Millennial Radio Classic"}

我知道.ToString()可以重载以提供此功能,但我不记得是否已在.NET中提供此功能。

4 个答案:

答案 0 :(得分:5)

您作为示例描述的格式与JSON非常相似,因此您可以使用JavaScriptSerializer

string value = new JavaScriptSerializer().Serialize(myItem);

答案 1 :(得分:5)

如果它不是你正在使用的JSON而且只是普通的C#类,那么请System.Reflection命名空间

类似的东西会起作用

Item item = new Item();
foreach (PropertyInfo info in item.GetType().GetProperties())
{
   if (info.CanRead)
   {

      // To retrieve value 
      object o = info.GetValue(myObject, null);

      // To Set Value
      info.SetValue("SKU", "NewValue", null);
   }
}

提供,您应该proper getset适合您想要合作的properties

答案 2 :(得分:1)

答案 3 :(得分:0)

您可以使用JSON库,例如JSON.NET或内置JavaScriptSerializer