Skip to content

Instantly share code, notes, and snippets.

@anzfactory
Created April 12, 2017 17:46
Show Gist options
  • Save anzfactory/51200a46343c3f244bc7eafc5cd8c9a2 to your computer and use it in GitHub Desktop.
Save anzfactory/51200a46343c3f244bc7eafc5cd8c9a2 to your computer and use it in GitHub Desktop.
配列の全要素を指定した型にキャストしちゃうぞっていう拡張
using System;
using System.Reflection;
using System.ComponentModel;
using System.Collections.Generic;
public static class ArrayExtension
{
public static TOutput[] ConvertAll<TInput, TOutput>(this TInput[] self, TOutput defaultValue)
{
Type type = typeof(TOutput);
TypeConverter converter = TypeDescriptor.GetConverter(type);
MethodInfo parseMethod = type.GetMethod("Parse", new Type[] { typeof(string) });
bool outputTypeIsString = defaultValue is string;
return Array.ConvertAll(self, target => {
TOutput result = defaultValue;
try {
if (parseMethod != null ) {
result = (TOutput)parseMethod.Invoke(null, new string[]{target.ToString()});
} else if (outputTypeIsString || converter.CanConvertFrom(typeof(TInput))) {
result = (TOutput)converter.ConvertFrom(target.ToString());
}
} catch (Exception e) {
// なにもしない
}
return result;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment