.NET 8 Preview 4 中的 Hot Reload 支持泛型方法修改
在 .NET 8 Preview 4 版本中,Hot Reload 新增了对修改泛型方法的支持,减少了需要重启应用程序才能使更改生效的情况。
Hot Reload 的功能
Hot Reload 允许开发者在应用程序运行时编辑代码并应用这些更改,而无需重启应用程序。此前,Hot Reload 已支持许多常见的 C# 功能,但在 .NET 8 Preview 4 之前不支持泛型。
实现泛型支持的技术要求
为了在运行时支持修改泛型,需要在 coreclr 中进行更改。因此,开发者需要使用 Visual Studio 17.7 preview 和 .NET 8 preview 4 来体验这些新功能。
支持的泛型修改场景
在 .NET 8 中,Hot Reload 支持以下四种泛型代码修改场景:
- 向泛型类型中添加新方法。
- 向(非)泛型类型中添加新的泛型方法。
- 编辑泛型类型中的现有方法。
- 编辑(非)泛型类型中的现有泛型方法。
代码示例
以下示例展示了如何格式化任何 IFormattable 类型为字符串:
static class FormattingHelpers
{
public static string ToString<T>(this T item, string format) where T : IFormattable
{
return item.ToString(format, CultureInfo.InvariantCulture);
}
}在 Hot Reload 支持泛型后,开发者可以在不停止应用程序的情况下,添加一个支持格式化可空值的新方法:
static class FormattingHelpers
{
public static string ToString<T>(this T item, string format) where T : IFormattable
{
return item.ToString(format, CultureInfo.InvariantCulture);
}
public static string ToString<T>(this T? item, string format) where T : struct, IFormattable
{
return item.Value.ToString(format, CultureInfo.InvariantCulture);
}
}由于支持编辑现有方法,开发者还可以动态扩展新方法以接受空值:
static class FormattingHelpers
{
public static string ToString<T>(this T item, string format) where T : IFormattable
{
return item.ToString(format, CultureInfo.InvariantCulture);
}
public static string ToString<T>(this T? item, string format) where T : struct, IFormattable
{
if (item == null)
{
return "";
}
return item.Value.ToString(format, CultureInfo.InvariantCulture);
}
}实际应用示例
在 Blazor 项目中,移除 First Name 字段及其帮助文本的标记会导致生成的泛型方法发生变化。在 .NET 8 之前,这种更改需要重启应用程序才能生效。现在,开发者可以通过点击 Visual Studio 中的 Hot Reload 图标来应用这些更改。
开发者社区的反馈
开发者社区对 Hot Reload 的改进表示欢迎,并希望了解哪些功能尚未支持以便追踪进展。此外,异步编程模型的支持仍然是开发者最期待的功能。
反馈与建议
.NET 团队鼓励开发者测试新功能并分享反馈,或在 GitHub 上提出希望 Hot Reload 支持的新场景。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用。你还可以使用@来通知其他用户。