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

2023-09-03 07:41:22 作者:Golven [流浪]

让我们说我有:

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

....

有没有在.NET中内置的方法,可以让我得到的属性和值的变量键入项目可能是这样的:

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"}

我知道的ToString()可以被重载来提供这种functionaility,但如果这是在.NET中已经提供了我不记得。

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 :

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