LoginSignup
1
1

More than 5 years have passed since last update.

複数の数値型が混在する配列をキャストする

Posted at

使うシーンが思いつきませんが。
以下のような配列の要素をすべてintにキャストしたい場合。

Program.cs
var array = new object[]
{
    (int)0,
    (short)1,
    (double)2.0,
    (decimal)3.0
};

これでは例外が発生してしまいます。

Program.cs
var intArray = array
    .Cast<int>()
    .ToArray();

そこでこんな拡張メソッドを用意します。

EnumerableUtility.cs
public static class EnumerableUtility
{
    public static IEnumerable<TResult> DynamicCast<TResult>(this IEnumerable source)
    {
        if (source == null) throw new ArgumentNullException("source");
        foreach (dynamic item in source)
        {
            yield return (TResult)item;
        }
    }
}

これで大丈夫。
ただ、普通の Cast と比べて遅いです。

Program.cs
var intArray = array
    .DynamicCast<int>()
    .ToArray();
1
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
1
1