Skip to content

Instantly share code, notes, and snippets.

@codewings
Last active December 22, 2015 08:38
Show Gist options
  • Save codewings/6445933 to your computer and use it in GitHub Desktop.
Save codewings/6445933 to your computer and use it in GitHub Desktop.
String Expression Converter
namespace StringExprConverter
{
class StringExprConverter
{
public static Object Format(String str, Type type)
{
if (String.IsNullOrEmpty(str))
return null;
if (type == null)
return str;
if (type.IsArray)
{
Type elementType = type.GetElementType();
String[] strs = str.Split(new char[] { ',' });
Array array = Array.CreateInstance(elementType, strs.Length);
for (int i = 0, c = strs.Length; i < c; ++i)
{
array.SetValue(ConvertSimpleType(strs[i], elementType), i);
}
return array;
}
return ConvertSimpleType(str,type);
}
private static object ConvertSimpleType(object value, Type destinationType)
{
object returnValue;
if ((value == null) || destinationType.IsInstanceOfType(value))
{
return value;
}
string str = value as string;
if ((str != null) && (str.Length == 0))
{
return null;
}
TypeConverter converter = TypeDescriptor.GetConverter(destinationType);
bool flag = converter.CanConvertFrom(value.GetType());
if (!flag)
{
converter = TypeDescriptor.GetConverter(value.GetType());
}
if (!flag && !converter.CanConvertTo(destinationType))
{
throw new InvalidOperationException("Cannot convert to:" + value.ToString() + "==>" + destinationType);
}
try
{
returnValue = flag ? converter.ConvertFrom(null, null, value) : converter.ConvertTo(null, null, value, destinationType);
}
catch (Exception e)
{
throw new InvalidOperationException("Failed to convert:" + value.ToString() + "==>" + destinationType, e);
}
return returnValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment