在默认的 Visual Studio Blazor WebAssembly 应用程序中,您将如何将 WeatherForecast class 移动到一个单独的项目中?
In the default Visual Studio Blazor WebAssembly app, how would you move the WeatherForecast class into a separate project?
如果我能解决这个问题,我可以将我的 Blazor Server 应用重做为 WebAssembly 应用。
开箱即用,WebAssembly 解决方案与 FetchData.razor 中的天气预报 class 显示如下:
我想重构它,以便在单独的 C# Class 库项目中将 WeatherForecast class 从 FetchData.razor 移动到 WeatherForecast.cs。
实现此目标需要对哪些位进行哪些更改?
天气预报 class,在单独的 class 库中,如下所示:
using System.Net.Http.Json;
namespace WeatherForecastNamespace
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string? Summary { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public static async Task<WeatherForecast[]?> GetWeatherForecasts(HttpClient Http)
{
return await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
}
}
}
并且 FetchData.razor @code 块,旧代码被注释掉,看起来像这样:
@code {
private WeatherForecast[]? forecasts;
protected override async Task OnInitializedAsync()
{
//forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
forecasts = await WeatherForecast.GetWeatherForecasts(Http);
}
//public class WeatherForecast
//{
// public DateTime Date { get; set; }
// public int TemperatureC { get; set; }
// public string? Summary { get; set; }
// public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
//}
}
如果此方法有任何问题,我将不胜感激。
如果我能解决这个问题,我可以将我的 Blazor Server 应用重做为 WebAssembly 应用。
开箱即用,WebAssembly 解决方案与 FetchData.razor 中的天气预报 class 显示如下:
我想重构它,以便在单独的 C# Class 库项目中将 WeatherForecast class 从 FetchData.razor 移动到 WeatherForecast.cs。
实现此目标需要对哪些位进行哪些更改?
天气预报 class,在单独的 class 库中,如下所示:
using System.Net.Http.Json;
namespace WeatherForecastNamespace
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string? Summary { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public static async Task<WeatherForecast[]?> GetWeatherForecasts(HttpClient Http)
{
return await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
}
}
}
并且 FetchData.razor @code 块,旧代码被注释掉,看起来像这样:
@code {
private WeatherForecast[]? forecasts;
protected override async Task OnInitializedAsync()
{
//forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
forecasts = await WeatherForecast.GetWeatherForecasts(Http);
}
//public class WeatherForecast
//{
// public DateTime Date { get; set; }
// public int TemperatureC { get; set; }
// public string? Summary { get; set; }
// public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
//}
}
如果此方法有任何问题,我将不胜感激。