9
4

【C#】nameof(T)という罠

Posted at

nameof(T)は罠

nameofにT(Generic型)を渡してはいけない(戒め)

例えばこんな感じのコードがあったとします。

getName.cs
public static string getName<T>()
{
    return nameof(T)
}

こんな結果が返ってきてほしいです。

nameofの願望.cs
// stringが返ってきてほしい
Console.WriteLine(getName<string>());

// intが返ってきてほしい
Console.WriteLine(getName<int>());

// floatが返ってきてほしい
Console.WriteLine(getName<float>());

しかしnameofはコンパイル時にこれらはすべてTとして解釈されてしまいます。

T、お前返ってくんな.cs
// Tが返ってくる
Console.WriteLine(getName<string>());

// Tが返ってくる
Console.WriteLine(getName<int>());

// Tが返ってくる
Console.WriteLine(getName<float>());

指定した型の名前を取得したい場合はtypeofでTypeを取得してからNameプロパティを取得しましょう。

getName.cs
public static string getName<T>()
{
    return typeof(T).Name
}

これでちゃんと返ってくるはずです。

やったー.cs
// stringが返ってくる
Console.WriteLine(getName<string>());

// intが返ってくる
Console.WriteLine(getName<int>());

// floatが返ってくる
Console.WriteLine(getName<float>());

(なんで1年の最後にこんな記事書いてるんだろう)

9
4
1

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
9
4