This is a follow-up to this question about converting values with reflection. Converting an object of a certain type to another type can be done like this:
object convertedValue = Convert.ChangeType(value, targetType);
Given two Type instances (say FromType and ToType), is there a way to test whether the conversion will succeed?
E.g. can I write an extension method like this:
public static class TypeExtensions
{
public static bool CanChangeType(this Type fromType, Type toType)
{
// what to put here?
}
}
EDIT: This is what I have right now. Ugly, but I don't see another way yet...
bool CanChangeType(Type sourceType, Type targetType)
{
try
{
var instanceOfSourceType = Activator.CreateInstance(sourceType);
Convert.ChangeType(instanceOfSourceType, targetType);
return true; // OK, it can be converted
}
catch (Exception ex)
{
return false;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…