报告并更新已弃用的 API
在 API 演进过程中,迟早需要引入重大更改。 传统的处理方式是使用 [已弃用] 属性标记已弃用的类型和成员,并通过该属性的消息解释如何迁移到新的 API。
ReSharper 提供了一种更优雅的解决方案,允许 API 用户查找并自动将旧 API 转换为新 API。 作为 API 作者,您需要使用 [CodeTemplate] 属性标记已过时的类型或成员,该属性来自 JetBrains.Annotations ,您可以在其中指定匹配旧 API 的搜索模式以及其替换模式。 该属性的工作方式类似于 结构化搜索和替换 模式,并作为自定义的 代码检查 ,与相应的 快速修复 和 范围内修复 一起使用。
[CodeTemplateAttribute] 被所有其他分析 C# 代码的 JetBrains 产品识别,例如 JetBrains Rider、 JetBrains Fleet 和 InspectCode 命令行工具。
让我们通过一个示例来看看它是如何工作的:
public class MyAssert
{
// Deprecated API. Usages look like:
// MyAssert.IsTrue(args.Length > 0);
public static void IsTrue(bool condition)
{
if (!condition)
throw new Exception("Assertion failed");
}
// New API. Usages should look like:
// MyAssert.That(args.Length > 0, Is.True);
public static void That<T>(T value, Constraint<T> constraint)
{
// ...
}
}
public class Constraint<T> { }
class Is
{
public static Constraint<bool> True => null;
public static Constraint<bool> False => null;
}
让我们使用 [代码模板] 属性注释已弃用的 IsTrue() 方法:
[CodeTemplate(
searchTemplate: "$member$($expr$)",
Message = "The API is deprecated, use 'MyAssert.That' instead",
ReplaceTemplate = "MyAssert.That($expr$, Is.True)",
ReplaceMessage = "Convert to 'MyAssert.That'")]
public static void IsTrue(bool condition)
{
if (!condition)
throw new Exception("Assertion failed");
}
现在 ReSharper 将报告所有 MyAssert.IsTrue() 的使用情况,并建议迁移修复:
![ReSharper:使用 [CodeTemplate] 属性为已弃用的 API 提供迁移修复建议 ReSharper:使用 [CodeTemplate] 属性为已弃用的 API 提供迁移修复建议](https://resources.jetbrains.com/help/img/dotnet/2025.2/CodeTemplateAttribute_example.png)
MyAssert.IsTrue(args.Length > 0);
MyAssert.That(args.Length > 0, Is.True);
最后修改日期: 2025年 9月 27日