开发者

Is there a built-in .NET method for getting all of the properties and values for an object?

开发者 https://www.devze.com 2022-12-28 17:13 出处:网络
Let\'s say I have: public class Item { public string SKU {get; set; } public string Descripti开发者_如何学运维on {get; set; }

Let's say I have:

public class Item
{
    public string SKU {get; set; }
    public string Descripti开发者_如何学运维on {get; set; }
}

....

Is there a built-in method in .NET that will let me get the properties and values for variable i of type Item that might look like this:

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

I know that .ToString() can be overloaded to provide this functionaility, but I couldn't remember if this was already provided in .NET.


The format you've described as an example looks a lot like JSON, so you could use the JavaScriptSerializer:

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


If it is not JSON you are using and just normal C# class, have alook at System.Reflection namespace

something similar would work

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);
   }
}

Provided with, you should have proper get and set in place for the properties you want to work over.


The XMLSerializer will work as well: http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx


You could use a JSON library such as JSON.NET or the built-in JavaScriptSerializer.

0

精彩评论

暂无评论...
验证码 换一张
取 消