非推奨の API を報告および更新する
API を進化させるときは、遅かれ早かれ重大な変更を導入する必要があります。 これに対処する従来の方法は、非推奨のタイプとメンバーを [Obsolete] 属性でマークし、属性のメッセージを使用して新しい 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] 属性でアノテーションを付けましょう。
[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/2026.1/CodeTemplateAttribute_example.png)
MyAssert.IsTrue(args.Length > 0);
MyAssert.That(args.Length > 0, Is.True);
2026 年 6 月 12 日