7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C#】ジェネリックの enum は、整数にキャストできない(やろうと思えば出来る)

Last updated at Posted at 2025-09-02

やろうとしたこと

こんなシチュエーションです。
色々調べましたが、列挙型から整数へのキャスト自体、このやり方だと出来ないっぽい?

internal abstract class Hoge<T>
    where T : Enum
{
    private int ToInt(T value)
        => (int)value; // エラー
}

解決方法

「整数に変換するメソッド」をクラス内で使いたいだけだったので、
そのメソッドを抽象にして、派生クラスで定義してもらうようにしました。

internal abstract class Hoge<T>
    where T : Enum
{
    private protected abstract int ToInt(T value);

    // ToInt() を使う
}

コメントからのアドバイス

1. Unsafe.BitCast が使える

公式リファレンス
列挙型のサイズが決まっているならば、このメソッドが有用。
自分のプロジェクトではbyteで統一しているので、↓↓こんな感じの拡張メソッドにしてみました。

internal static class MyExtension
{
    internal static byte ToByteInteger<TEnum>(this TEnum value)
        where TEnum : Enum
        => Unsafe.BitCast<TEnum, byte>(value);
}
7
2
2

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
7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?