Convert 类不能处理 Nullable 类型,所以我必须对它们进行特殊处理。
static void Main(string[] args)
{
var strings = new[] { "1","2","3"};
var ints = strings.ConvertItems<string, int>().ToList();
var doubles = strings.ConvertItems<string, double>().ToList();
var nullableints = strings.ConvertItems<string, int?>().ToList();
}
public static IEnumerable<TargetType> ConvertItems<SourceType, TargetType>(this IEnumerable<SourceType> sourceCollection)
{
var targetType = typeof(TargetType);
if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
targetType = targetType.GetGenericArguments().First();
}
return sourceCollection.ConvertItems((source) => (TargetType)Convert.ChangeType(source, targetType));
}
public static IEnumerable<TargetType> ConvertItems<SourceType, TargetType>(this IEnumerable<SourceType> sourceCollection, Converter<SourceType, TargetType> convertor)
{
foreach (var item in sourceCollection)
{
yield return convertor(item);
}
}
编辑:弱类型版本,当您只知道运行时的类型时
static void Main(string[] args)
{
var strings = new[] { "1","2","3"};
var ints = strings.ConvertItems(typeof(int));
var doubles = strings.ConvertItems(typeof(double));
var nullableints = strings.ConvertItems(typeof(int?));
foreach (int? item in nullableints)
{
Console.WriteLine(item);
}
}
public static IEnumerable ConvertItems(this IEnumerable sourceCollection,Type targetType)
{
if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
targetType = targetType.GetGenericArguments().First();
}
foreach (var item in sourceCollection)
{
yield return Convert.ChangeType(item, targetType);
}
}