Let's say I have:
public class Item
{
public string SKU {get; set; }
public string Description {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.
您作为示例描述的格式看起来很像JSON ,因此您可以使用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.
XMLSerializer也可以运行: http : //msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx
您可以使用JSON库,例如JSON.NET或内置的JavaScriptSerializer 。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.