示例2:显式拓展
通过声明一个显式拓展(explict extension
),我们可以使用类型转换将类型转换为拓展的类型并获得相应的成员
有如下天气数据JSON
{
"type": "clear",
"tempMax": 32,
"tempMin": 20,
"hourly": [
{
"time": "2024-06-09T00:00",
"type": "cloudy",
"temp": 20
},
{
"time": "2024-06-09T06:00",
"type": "clear",
"temp": 24
},
{
"time": "2024-06-09T12:00",
"type": "clear",
"temp": 32
},
{
"time": "2024-06-09T18:00",
"type": "cloudy",
"temp": 26
},
{
"time": "2024-06-09T23:00",
"type": "rain",
"temp": 21
}
]
}
定义如下显式拓展:
explicit extension DailyWeather for JsonElement
{
public string WeatherType => this.GetProperty("type").GetString()!;
public string MaxTemperature => this.GetProperty("tempMax").GetString()!;
public string MinTemperature => this.GetProperty("tempMin").GetString()!;
public IEnumerable<HourlyWeather> HourlyForecasts => this.GetProperty("hourly")!.EnumerateArray();//此处有隐式类型转换
}
explicit extension HourlyWeather for JsonElement
{
public DateTime Time => this.GetProperty("time").GetDateTime()!;
public int Temperature => this.GetProperty("temp").GetInt32()!;
public string WeatherType => this.GetProperty("type").GetString()!;
}
现在,我们可以用类型安全的方式访问JSON中的内容
var data = jsonData.ParseAsJson();
var weather = (DailyWeather)data;
Console.WriteLine($"今日天气:{weather.WeatherType}");
foreach(HourlyWeather hourly in weather.HourlyForecasts)//此处有隐式类型转换
{
Console.WriteLine($"{hourly.Time.Hour}时的天气:{hourly.WeatherType}");
}