[英]Just started learning C# & ASP.NET - strange syntax (to me) and I don't know what it is
所以我在看微軟在 ASP.Net 上提供的教程
他們創建了一個名為 class 的產品,如下所示:
public class Product
{
public string Id { get; set; }
public string Maker { get; set; }
[JsonPropertyName("img")]
public string Image { get; set; }
public string Url { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int[] Ratings { get; set; }
public override string ToString() => JsonSerializer.Serialize<Product>(this);
}
我不知道這是什么
[JsonPropertyName("img")]
我不知道如何在谷歌上搜索它。
我不明白那些方括號是什么(它們應該定義一個數組,但在這種情況下它們的意義何在?)
另外,整條線的意義何在? 它有什么作用?
謝謝。
在 c# 中,您可以像這樣定義 arrays:
string[] companies = new string[3] {"Google", "Microsoft", "Facebook"}; //3 is the size and it's necessary when defining array without items. (It isn't necessary now)
因此,與 python 或 javascript 不同,數組項不在方括號內。
但是還有一種叫做屬性的東西。
屬性是從Attribute
class 繼承的特殊類,您可以在您希望屬性應用到它的屬性或方法或變量之前的方括號中使用該 class 的構造函數。 在此示例中,您將JsonPropertyName
屬性應用於Image
,如下所示:
[JsonPropertyName("img")]
public string Image { get; set; }
JsonSerializer.Serialize<Product>(this)
將檢查每個屬性的屬性(如果有的話)並在序列化時應用該屬性。 當您使用重寫的ToString()
方法序列化此 class 的實例時,此屬性會強制序列化程序將 img 用於 JSON 屬性名稱而不是 Image,因此您將在 Z0ECD11C1D7A287A278D1 中獲得 img 而不是 Image。
不使用屬性的示例:
{
"Id": <Id>,
"Maker": <Maker>,
"Image": <Image>, //Image
"Url": <Url>,
"Title": <Title>,
"Description": <Description>,
"Ratings": [<Ratings>]
}
但是當你使用[JsonPropertyName("img")]
屬性時,它看起來像這樣:
{
"Id": <Id>,
"Maker": <Maker>,
"img": <Image>, //img
"Url": <Url>,
"Title": <Title>,
"Description": <Description>,
"Ratings": [<Ratings>]
}
它描述並給出了一個底部屬性的一些特性。 您可以將其搜索為“C# 中的屬性”。 你會得到很多他們的文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.