Created
April 12, 2017 17:46
-
-
Save anzfactory/51200a46343c3f244bc7eafc5cd8c9a2 to your computer and use it in GitHub Desktop.
配列の全要素を指定した型にキャストしちゃうぞっていう拡張
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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