LoginSignup
0
1

.NET Standard 2.0 対応の覚書

Posted at

.NET 6.0で作成していたライブラリを.NET Standard 2.0に対応する必要があるときの覚書

プロジェクトファイルの設定

  • *.csprojを開き、TargetFrameworkTargetFrameworksに変更し、;で区切ってnetstandard2.0を追加する
  • LangVersionタグを追加し、値を9.0とする
変更前
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    ~省略~
  </PropertyGroup>
</Project>
変更後
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFrameworks>net6.0;netstandard2.0</TargetFrameworks>
    <LangVersion>9.0</LangVersion>
    ~省略~
  </PropertyGroup>
</Project>

initの有効化

  • IsExternalInitクラスを追加する
IsExternalInit.cs
using System.ComponentModel;

namespace System.Runtime.CompilerServices
{
  /// <summary>
  /// Reserved to be used by the compiler for tracking metadata.
  /// This class should not be used by developers in source code.
  /// This dummy class is required to compile records when targeting .NET Standard
  /// </summary>
  [EditorBrowsable(EditorBrowsableState.Never)]
  internal static class IsExternalInit
  {
  }
}

メソッドが対応していない場合

コンパイルエラーが出る場合は下記を試してみる

NuGetで探す

  • 利用していた属性が見つからない場合等、NuGetパッケージの管理で探してみる
    • 例:System.ComponentModel.DataAnnotations.Schema.ColumnAttribute属性が見つからない

      → アセンブリ名System.ComponentModel.Annotationsで検索

書き方を変更する

  • ifディレクティブで対応している書き方に変える
    • 例:Enum.GetValuesメソッドがジェネリック版に対応していない
変更前
public void Sample()
{
  foreach (var value in Enum.GetValues<TypeCode>())
  {
    // 処理
  }
}
変更後
public void Sample()
{
#if NETSTANDARD2_0
  foreach (TypeCode value in Enum.GetValues(typeof(TypeCode)))
#else
  foreach (var value in Enum.GetValues<TypeCode>())
#endif
  {
    // 処理
  }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1