- 封装类
namespace EFCoreDynamicCondition.Helptool
{
public class Helptool
{
public static T ConvertToType<T>(object value)
{
try
{
return (T)Convert.ChangeType(value, typeof(T));
}
catch (InvalidCastException)
{
Console.WriteLine($"Conversion to {typeof(T).Name} failed.");
return default(T);
}
}
public static object ConvertToType(object value, Type targetType)
{
try
{
return Convert.ChangeType(value, targetType);
}
catch (InvalidCastException)
{
Console.WriteLine($"Conversion to {targetType.Name} failed.");
return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;
}
}
}
}
- 使用demo
Console.WriteLine(Helptool.ConvertToType<int>("32"));
Console.WriteLine(Helptool.ConvertToType("32", typeof(int)));
Console.WriteLine("Hello, World!");