動くコード図鑑技術記事現場の渡り方キャリア論すべての記事About
C#

パターン4: where T : IDisposable — Interface実装制約

出典: C# Generic 制約 (where T : …) — 業務SE が型安全コードを書く5パターンパターン4: where T : IDisposable — Interface実装制約

パターン4: where T : IDisposable — Interface実装制約 (csharp)#13cf670d5462
// ✅ TはIDisposable実装のみ
public class DisposableScope<T> where T : IDisposable
{
    private readonly T _resource;
 
    public DisposableScope(T resource)
    {
        _resource = resource;
    }
 
    public void Use(Action<T> action)
    {
        using (_resource)// TがIDisposableなのでusingで囲める
        {
            action(_resource);
        }
    }
}
 
//使い方
using (var conn = new SqlConnection("..."))
{
    var scope = new DisposableScope<SqlConnection>(conn);
    scope.Use(c => c.Open());
}
▸ この snippet は実行結果未収録
▸ 実行結果は未収録です
  • id: #13cf670d5462
  • lines: 25
  • extracted: 2026-06-10

Source収録記事

この snippet は記事の「パターン4: where T : IDisposable — Interface実装制約」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。

同じ記事から

9
図鑑トップ