在C#中,要在运行时转换泛型类型,可以使用反射和泛型方法。以下是一个示例,说明如何在运行时将泛型类型转换为另一个泛型类型:
using System;
public class Program
{
public static void Main()
{
string input = "Hello, World!";
object obj = input;
string output = ConvertGenericType<string, string>(obj);
Console.WriteLine(output);
}
public static TOutput ConvertGenericType<TInput, TOutput>(object input)
{
Type inputType = typeof(TInput);
Type outputType = typeof(TOutput);
// 使用Convert.ChangeType方法进行基本类型的转换
if (inputType.IsPrimitive && outputType.IsPrimitive)
{
return (TOutput)Convert.ChangeType(input, typeof(TOutput));
}
// 如果输入类型和输出类型相同,则直接返回输入对象
if (inputType == outputType)
{
return (TOutput)input;
}
// 如果输出类型是泛型类型,则尝试将输入类型转换为泛型类型
if (outputType.IsGenericType)
{
Type genericTypeDefinition = outputType.GetGenericTypeDefinition();
Type[] genericArguments = outputType.GetGenericArguments();
// 如果泛型类型是列表类型,则尝试将输入类型转换为列表类型
if (genericTypeDefinition == typeof(List<>))
{
Type listType = typeof(List<>).MakeGenericType(genericArguments);
object list = Activator.CreateInstance(listType);
foreach (object item in (IEnumerable)input)
{
object convertedItem = ConvertGenericType<object, object>(item);
listType.GetMethod("Add").Invoke(list, new[] { convertedItem });
}
return (TOutput)list;
}
// 如果泛型类型是字典类型,则尝试将输入类型转换为字典类型
if (genericTypeDefinition == typeof(Dictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
object dictionary = Activator.CreateInstance(dictionaryType);
foreach (DictionaryEntry entry in (IDictionary)input)
{
object key = ConvertGenericType<object, object>(entry.Key);
object value = ConvertGenericType<object, object>(entry.Value);
dictionaryType.GetMethod("Add").Invoke(dictionary, new[] { key, value });
}
return (TOutput)dictionary;
}
}
// 如果无法进行转换,则抛出异常
throw new InvalidOperationException($"无法将类型 {inputType} 转换为类型 {outputType}");
}
}
在这个示例中,我们定义了一个名为ConvertGenericType
的泛型方法,该方法接受两个泛型参数,分别表示输入类型和输出类型。我们使用反射和泛型方法来检查输入类型和输出类型,并根据需要进行转换。
请注意,这个示例仅用于演示目的,并不是一个完整的解决方案。在实际应用中,您可能需要根据您的需求进行更多的错误检查和类型转换。
领取专属 10元无门槛券
手把手带您无忧上云