3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[C#4.0以降] unboxingとcastが同時にできない問題を回避する方法

Posted at

静的型付け言語のC#では、unboxing(up-castした型から元の型にdown-castする)

object obj = (object)10; // intからobjectにup-cast
int intValue = (int)obj; // unboxing, down-cast, 例外は発生しない

とcastを同時に行うことができません。

byte byteValue = (byte)(object)10;       // InValidCast例外, int -> object -> byte
double doubleValue = (double)(object)10; // InValidCast例外, int -> object -> double

T returnZero<T>(){
  return (T)(object)0; // InValidCast例外 int -> object -> T
}
var byteValue = returnZero<byte>();
var doubleValue = returnZero<double>();

あまり良い方法ではないのですが、C#4.0から導入されたdynamicを用いると、この問題を回避できます。

byte byteValue = (byte)(dynamic)10;
double doubleValue = (double)(dynamic)10;

dynamic便利ですね。幅広いコーディングが出来ます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?