Usage first:
TConverter.ChangeType<T>(StringValue);
The class is below.
public static class TConverter
{
public static T ChangeType<T>(object value)
{
return (T)ChangeType(typeof(T), value);
}
public static object ChangeType(Type t, object value)
{
TypeConverter tc = TypeDescriptor.GetConverter(t);
return tc.ConvertFrom(value);
}
public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter
{
TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));
}
}
Ref: http://stackoverflow.com/questions/8625/generic-type-conversion-from-string
Example of Console Application below.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(TConverter.ChangeType<float>("00454545458"));
Console.ReadKey();
//Usage
DateTime datetime = GenericConverter.Parse<DateTime>("12.10.2007");
Console.WriteLine(datetime);
IFormatProvider providerEN = new System.Globalization.CultureInfo("en-US", true);
IFormatProvider providerTR = new System.Globalization.CultureInfo("tr-TR", true);
DateTime x = GenericConverter.Parse<DateTime>("12.10.2007", providerTR); // ddMMyyyy
Console.WriteLine(x);
DateTime y = GenericConverter.Parse<DateTime>("12.10.2007", providerEN); // MMddyyyy
Console.WriteLine(y);
int iValue = GenericConverter.Parse<int>("12");
Console.WriteLine(iValue);
Console.ReadKey();
}
}
public class GenericConverter
{
public static T Parse<T>(string sourceValue) where T : IConvertible
{
return (T)Convert.ChangeType(sourceValue, typeof(T));
}
public static T Parse<T>(string sourceValue, IFormatProvider provider) where T : IConvertible
{
return (T)Convert.ChangeType(sourceValue, typeof(T), provider);
}
}
public static class TConverter
{
public static T ChangeType<T>(object value)
{
return (T)ChangeType(typeof(T), value);
}
public static object ChangeType(Type t, object value)
{
TypeConverter tc = TypeDescriptor.GetConverter(t);
return tc.ConvertFrom(value);
}
public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter
{
TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));
}
}
Comments
Post a Comment