C# WPF: 使用泛型和反射将字符串转换为指定类型
使用泛型和反射创建一个通用方法,将字符串转换为指定泛型类型。可以使用以下代码实现:
public static T ConvertTo<T>(string value)
{
Type type = typeof(T);
MethodInfo method = type.GetMethod('Parse', new[] { typeof(string) });
if (method != null)
{
object result = method.Invoke(null, new object[] { value });
return (T)result;
}
return default(T);
}
该方法接受一个字符串和一个泛型类型参数 T,并使用反射获取 T 类型的 Parse 方法。如果找到了 Parse 方法,则将字符串值传递给该方法并返回转换后的结果。如果未找到 Parse 方法,则返回 T 类型的默认值。使用示例:
int intValue = ConvertTo<int>('123');
double doubleValue = ConvertTo<double>('3.14');
boolean boolValue = ConvertTo<bool>('true');
原文地址: https://www.cveoy.top/t/topic/kgE7 著作权归作者所有。请勿转载和采集!