Method definition:
private static T getvaluebykey<t> (string key) where t:iconvertible
{
T Localval=default (t);
string strtype = typeof (T). Name;
String valuesdata = Configurationmanager.appsettings[key]. ToString ();
Localval = (t) convert.changetype (Valuesdata, typeof (T));
return localval;
}
Public Static Tconverttype Doconvert<Tconverttype> (ObjectConvertvalue, OutBOOL Hasconverted){hasconverted= False; VarConverted= Default(Tconverttype); Try {Converted= (Tconverttype) Convert.ChangeType(Convertvalue, typeof(Tconverttype));hasconverted= True; } Catch (InvalidCastException) { } Catch (argumentnullexception) { } catch (formatexception) {< Span class= "PLN" > } catch (overflowexception) {< Span class= "PLN" > } return Converted}
Syntax two:
public static Tconverttype doconvert<tconverttype> (object Convertvalue, out bool hasconverted)
{
hasconverted = false;
var converted = default (Tconverttype);
Try
{
converted = (Tconverttype)
Convert.changetype (Convertvalue, typeof (Tconverttype));
Hasconverted = true;
}
catch (InvalidCastException)
{
}
catch (ArgumentNullException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
return converted;
}
Call:
Getvaluebykey<string> ("AAA");
Getvaluebykey<int> ("BBB");
Reference: Http://stackoverflow.com/questions/8171412/cannot-implicitly-convert-type-int-to-t
The type (int,string,...) Convert to Type T